<?php


namespace app\manage\controller;

use other\MessageSend;
use other\SmsMuSend;
use other\SmsWYSend;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use Predis\Command\Redis\TIME;
use think\Db;
use think\Log;
use app\api\controller\v1\Clue as ClueModel;
use think\Queue;

class Clue extends Base
{
    public function _initialize()
    {
        parent::_initialize();
    }

    public function index()
    {

        // 查询条件start
        $clue_id = input('clue_id','');
        $clue_name = input('clue_name','');
        $phone = input('phone','');
        $source = input('source','0');
        $status = input('status/d',99);
        $times = input('times','');
        $times2 = input('times2','');
        $pro_id = input('pro_id','');
        $city = input('city','');
        $num = input('num','');
        $err_msg = input('err_msg','');
        $cityname = input('cityname','');
        $ac_name = input('ac_name','');
        $adv_id = input('adv_id','');
        $mer_name = input('mer_name','');
        $channel_id = input('channel_id','');
        $pstatus = input('pstatus/a','');
        $is_find = input('is_find','');
        $is_not_push = input('is_not_push','');
        $is_follow = input('is_follow','');
        $shangwu_admin_id = input('shangwu_admin_id','');
        $youhua_id = input('youhua_id','');

        $map = [];
        //优化师
        if($youhua_id!=''){
            $map['act.bind_youhua']=$youhua_id;
        }
        if($clue_id){
            $map['a.clue_id']=['like','%'.$clue_id.'%'];
        }
        if($clue_name != ''){
            $map['a.clue_name'] = ['like','%'.$clue_name.'%'];
        }
        if($phone != 0){
            $map['a.phone'] = $phone;
        }
//        if($source != '0'){
//            $map['source'] = $source;
//        }
        if($times != ''){
            $time_arr = explode(' - ',$times);
            $map['a.create_time'] = ['between',[strtotime($time_arr[0]),strtotime($time_arr[1])]];
        }

        if($times2 != ''){
            $time_arr = explode(' - ',$times2);
            $map['b.create_time'] = ['between',[strtotime($time_arr[0]),strtotime($time_arr[1])]];
        }
        if($status!=99){
            $map['a.status']=$status;
        }
        if($pro_id!=''){
            $map['a.pro_id|a.pro_id2']=$pro_id;
        }
        if(!empty($city)){
            $map['a.city']=$city;
        }
        if(!empty($err_msg)){
            $map['a.clue_id'] = ['in' , model('ClueErrorLog')->where('title','like','%'.$err_msg.'%')->order('id desc')->column('clue_id')];
            //$map['a.err_msg']=['like','%'.$err_msg.'%'];
        }

        if($adv_id){
            $map['a.adv_id']=$adv_id;
        }
        if($channel_id){
            $map['a.type']=$channel_id;
        }

        if($is_find!=''){
            $map['b.is_find']=$is_find;
        }
        if($is_not_push!=''){
            $map['a.is_not_push']=$is_not_push;
        }

        if($is_follow!=''){
            $map['b.is_follow']=$is_follow;
        }

        if(!empty($pstatus)){
            if(count($pstatus)==1&&$pstatus[0]==0){

            }else{
                $map['b.progress_status']=['in',$pstatus];
            }
        }

        if(!empty($mer_name)){
            $mArr=model('Merchant')->where('mer_name','like','%'.$mer_name.'%')->column('id');
            if($mArr){
                $map['b.mer_id']=['in',$mArr];
            }else{
                $map['a.id']=0;
            }
        }
        //模糊查询城市
        $map_city = "";
        if(!empty($cityname)){
            $cityIdArr=Db::name('city')->field('id,type,pid')->where('name','like',$cityname."%")->where('type',2)->find();
            if($cityIdArr){
                $city = $cityIdArr['pid'].'-'.$cityIdArr['id'];
                $map_city=" a.city = '{$city}' or a.clue_city = '{$city}' ";
            }
        }
        if(!empty($ac_name)){
            $adv_idArr=model('Account')->where('acc_name','like','%'.$ac_name.'%')->column('adv_id');
            if(!empty($adv_idArr)){
                $map['a.adv_id']=['in',$adv_idArr];
            }else{
                $map['a.adv_id']=0;
            }
        }


        if($this->group_id==7){
            $accIdArr=model('Account')->where('bind_youhua',$this->uid)->column('id');
            if(empty($accIdArr)){
                $map['a.account_id']=0;
            }else{
                $map['a.account_id']=['in',$accIdArr];
            }
        }

        //商务管理员
        if (!empty($shangwu_admin_id)) {
            $ids = \db('merchant')->alias('m')
                ->join('admin a', 'm.bind_aid = a.id')
                ->where('a.realname', 'like', "%".$shangwu_admin_id."%")
                ->column('m.id');
            $map['c.id'] = ['in', $ids];
        }

        // 查询条件end

        $channels = $this->getChannelArray();
//        $products = model('Product')->getListByMap();
        $productAll =Db::name('product')->column('name','id');
        $products = model('Product')->where('status',1)->column('name','id');

        $merchants = model('Merchant')->getListByMap([],'','',false);

        if(empty($num)||$num<2){
            $infosRe = model('Clue')->field('phone,count(id) cnum')->group('phone')->having('cnum >= 2')->select();
        }else{
            $infosRe = model('Clue')->field('phone,count(id) cnum')->group('phone')->having('cnum >='.$num)->select();
            if($infosRe){
                $map['a.phone']=['in',array_column($infosRe,'phone')];
            }

        }

        $statusArr=Db::name('clue_progress_status')->order('sort desc')->select();
        $statusList=array_column($statusArr,'name','id');
        $endStatus=[];
        foreach ($statusArr as $v){
            if($v['status']==1&&empty($v['delete_time'])){
                $endStatus[]=['id'=>$v['id'],'name'=>$v['name']];
            }
        }


        $infos = model('Clue')->alias('a')->field('a.*,c.mer_name,c.mer_desc,c.username,c.phone mphone,b.push_type,show_city,is_find,b.city push_city,b.progress_status,b.push_channel')
            ->join('clue_log b','a.id=b.clue_id','LEFT')
            ->join('merchant c','c.id=b.mer_id','LEFT')
            ->join('account act','a.adv_id=act.adv_id','LEFT')
            ->order('a.id desc')
            ->where($map)
            ->where($map_city)
            ->paginate();

//        dump($infos);die;
//            ->getInfosByMap($map, '', false);

        foreach ($infos as $k=>$v){

            // 显示城市
            if (!empty($v['show_city'])) {
                if (strpos($v['show_city'], "-") !== false) {
                    $ids = explode('-',$v['show_city']);
                    $prov = $this->getCityName($ids[0]);
                    $city = $this->getCityName($ids[1]);
                    if($prov == $city){
                        $infos[$k]['show_city'] = $prov;
                    }else{
                        $infos[$k]['show_city'] = $prov.'-'.$city;
                    }
                } else {
                    $infos[$k]['show_city'] = $v['show_city'];
                }
            }

            if(!empty($v['progress_status'])){
                $infos[$k]['progress_status']='状态：'.$statusList[$v['progress_status']];
            }else{
                $infos[$k]['progress_status']='';
            }

            $infos[$k]['re_num']='';
            foreach ($infosRe as $val){
                if($v['phone']==$val['phone']){
                    $infos[$k]['re_num']=$val['cnum'];
                }
            }

            $infos[$k]['product_name']=empty($v['pro_id'])?'未知':$productAll[$v['pro_id']];
            $infos[$k]['product_name2']=empty($v['pro_id2'])?'':$productAll[$v['pro_id2']];

            $city1=$v['city'];
            $city2=$v['clue_city'];
            if($v['city'] != ''){
                $ids = explode('-',$v['city']);
                $cityNum=count($ids);
                if($cityNum==1){
                    $infos[$k]['city'] = $this->getCityName($ids[0]);
                }elseif ($cityNum==2){
                    $prov = $this->getCityName($ids[0]);
                    $city = $this->getCityName($ids[1]);
                    if($prov == $city){
                        $infos[$k]['city'] = $prov;
                    }else{
                        $infos[$k]['city'] = $prov.'-'.$city;
                    }
                }
            }

            if($v['clue_city'] != ''){
                $ids = explode('-',$v['clue_city']);
                $cityNum=count($ids);
                if($cityNum==1){
                    $infos[$k]['clue_city'] = $this->getCityName($ids[0]);
                }elseif ($cityNum==2){
                    $prov = $this->getCityName($ids[0]);
                    $city = $this->getCityName($ids[1]);
                    if($prov == $city){
                        $infos[$k]['clue_city'] = $prov;
                    }else{
                        $infos[$k]['clue_city'] = $prov.'-'.$city;
                    }
                }
            }

            if($v['mobile_city'] != ''){
                $ids = explode('-',$v['mobile_city']);
                $cityNum=count($ids);
                if($cityNum==1){
                    $infos[$k]['mobile_city'] = $this->getCityName($ids[0]);
                }elseif ($cityNum==2){
                    $prov = $this->getCityName($ids[0]);
                    $city = $this->getCityName($ids[1]);
                    if($prov == $city){
                        $infos[$k]['mobile_city'] = $prov;
                    }else{
                        $infos[$k]['mobile_city'] = $prov.'-'.$city;
                    }
                }
            }

            if($v['push_city']==$city1){
                $v['push_city']= $infos[$k]['city'];
            }elseif ($v['push_city']==$city2){
                $v['push_city']= $infos[$k]['clue_city'];
            }else{
                $ids = explode('-',$v['push_city']);
                $cityNum=count($ids);
                if($cityNum==1){
                    $infos[$k]['push_city'] = $this->getCityName($ids[0]);
                }elseif ($cityNum==2){
                    $prov = $this->getCityName($ids[0]);
                    $city = $this->getCityName($ids[1]);
                    if($prov == $city){
                        $infos[$k]['push_city'] = $prov;
                    }else{
                        $infos[$k]['push_city'] = $prov.'-'.$city;
                    }
                }
            }


            if($v['push_time']){
                $infos[$k]['push_time'] = date('Y-m-d H:i:s',$v['push_time']);
            }

            $infos[$k]['acc_name'] = '手动添加的线索';
            $infos[$k]['acc_desc'] = '手动添加';
            $infos[$k]['channel_name'] = '后台系统';
            if($v['adv_id'] != ''){
                $account = Db::name('account')->where('adv_id','=',$v['adv_id'])->find();
                if($account){
                    $infos[$k]['acc_name'] = $account['acc_name'];
                    $infos[$k]['acc_desc'] = $account['acc_desc'];
                    $infos[$k]['channel_name'] = $channels[$account['channel_id']];
                }else{
                    $infos[$k]['acc_name'] = '未知账号';
                    $infos[$k]['acc_desc'] = '';
                    $infos[$k]['channel_name'] = $channels[$v['type']];
                }
            }
            if(empty($v['remark'])){
                $infos[$k]['remark_data']=[];
            }else{
                $remark=json_decode($v['remark'],true);
                if (is_array($remark)){
                    $remarkArr=[];
                    $keys=array_keys($remark);
                    $b=false;//默认索引
                    //判断关联数组还是索引数组
                    foreach($keys as $value){
                        if(!is_int($value)){
                            $b=true;
                            break;
                        }
                    }
                    //是关联数组
                    if($b){
                        foreach ($remark as $kk=>$vv){
                            if ($kk == "称呼" || $kk == "电话") {
                                continue;
                            }
                            if($kk=='城市'){
                            }else{
                                $remarkArr[]=$kk.'：'.$vv;
                            }
                        }
                    }else{
                        foreach ($remark as $vv){
                            if($v['type']==1){
                                if(isset($vv['name'])&&isset($vv['value'])){
                                    if ($vv['name'] == "称呼" || $vv['name'] == "电话") {
                                        continue;
                                    }
                                    if($vv['name']=='城市'){
                                    }else{
                                        $remarkArr[]=$vv['name'].'：'.$vv['value'];
                                    }
                                }else{
                                    $remarkArr[]=json_encode($vv,JSON_UNESCAPED_UNICODE);
                                }
                            }else{
                                if(isset($vv['name'])&&isset($vv['value'])){
                                    if ($vv['name'] == "称呼" || $vv['name'] == "电话") {
                                        continue;
                                    }
                                    $remarkArr[]=$vv['name'].'：'.$vv['value'];
                                }else{
                                    $remarkArr[]=json_encode($vv,JSON_UNESCAPED_UNICODE);
                                }
                            }
                        }
                    }
                }else{
                    $remarkArr=[];
                    $remarkArr[]=$v['remark'];

                }
                $infos[$k]['remark_data']=$remarkArr;
            }

            $infos[$k]['progress']=model('ClueProgress')->where('clue_id',$v['id'])->order('id desc')->select();

            $infos[$k]['error_log']=[];
            if($v['status']==0){
                $infos[$k]['error_log']=model('ClueErrorLog')->where('clue_id',$v['clue_id'])->order('id desc')->limit(0,8)->select();
            }

        }

//        $sources = Db::name('clue')->field('source')->where('source','<>','')->group('source')->select();

        $province = Db::name('city')->where(['pid'=>1])->select();
//        $this->assign('province',$province);
//        dump($infos);die;

//        dump($infos->total());die;

        if(is_array($pstatus)){
            $pstatus=implode(',',$pstatus);
        }else{
            $pstatus=0;
        }

        $shangwu_admin = model('AuthGroupAccess')->alias('a')
            ->field('a.*,b.phone,b.realname')
            ->join('admin b','a.uid=b.id')
            ->where(function ($q){
                $q->where('a.group_id','in', [4, 5]);
            })
//        ->where('a.group_id',4)
            ->where('b.delete_time',NULL)->select();

        $youhua = model('AuthGroupAccess')->alias('a')
            ->field('a.*,b.phone,b.realname')
            ->join('admin b','a.uid=b.id')
            ->where(function ($q){
                $q->where('a.group_id',7);
            })
//        ->where('a.group_id',4)
            ->where('b.delete_time',NULL)->select();

        return $this->fetch('',[
            'infos' => $infos,
            'clue_name' => $clue_name,
            'phone' => $phone,
            'source' => $source,
            'times' => $times,
            'times2' => $times2,
            'sources' => [],
            'province' => $province,
            'status' => $status,
            'pro_id' => $pro_id,
            'products' => $products,
            'num' => $num,
            'err_msg' => $err_msg,
            'cityname' => $cityname,
            'ac_name' => $ac_name,
            'adv_id' => $adv_id,
            'mer_name' => $mer_name,
            'merchants' => $merchants,
            'channels' => $channels,
            'channel_id' => $channel_id,
            'clue_id' => $clue_id,
            'endStatus' => $endStatus,
            'pstatus' => $pstatus,
            'is_find' => $is_find,
            'is_not_push' => $is_not_push,
            'is_follow' => $is_follow,
            'group_id'=>$this->group_id,
            'shangwu_admin' => $shangwu_admin,
            'shangwu_admin_id' => $shangwu_admin_id,
            'youhua' => $youhua,
            'youhua_id' => $youhua_id,
            'accounts' => \db('account')->where('status', 1)->order('id desc')->select(),
        ]);
    }

    //导出线索成本明细
    public function indexExport()
    {
        // 查询条件start
        $clue_id = input('clue_id','');
        $clue_name = input('clue_name','');
        $phone = input('phone','');
        $source = input('source','0');
        $status = input('status/d',99);
        $times = input('times','');
        $times2 = input('times2','');
        $pro_id = input('pro_id','');
        $city = input('city','');
        $num = input('num','');
        $err_msg = input('err_msg','');
        $cityname = input('cityname','');
        $ac_name = input('ac_name','');
        $adv_id = input('adv_id','');
        $mer_name = input('mer_name','');
        $channel_id = input('channel_id','');
        $pstatus = input('pstatus/a','');
        $is_find = input('is_find','');
        $is_not_push = input('is_not_push','');
        $is_follow = input('is_follow','');
        $sortBy = input('orderBy','');

        $map = [];
        if($clue_id){
            $map['a.clue_id']=$clue_id;
        }
        if($clue_name != ''){
            $map['a.clue_name'] = ['like','%'.$clue_name.'%'];
        }
        if($phone != 0){
            $map['a.phone'] = $phone;
        }
//        if($source != '0'){
//            $map['source'] = $source;
//        }
        if($times != ''){
            $time_arr = explode(' - ',$times);
            $map['a.create_time'] = ['between',[strtotime($time_arr[0]),strtotime($time_arr[1])]];
        }

        if($times2 != ''){
            $time_arr = explode(' - ',$times2);
            $map['b.create_time'] = ['between',[strtotime($time_arr[0]),strtotime($time_arr[1])]];
        }
        if($status!=99){
            $map['a.status']=$status;
        }
        if($pro_id!=''){
            $map['a.pro_id']=$pro_id;
        }
        if(!empty($city)){
            $map['a.city']=$city;
        }
        if(!empty($err_msg)){
            $map['a.err_msg']=['like','%'.$err_msg.'%'];
        }

        if($adv_id){
            $map['a.adv_id']=$adv_id;
        }
        if($channel_id){
            $map['a.type']=$channel_id;
        }

        if($is_find!=''){
            $map['b.is_find']=$is_find;
        }
        if($is_not_push!=''){
            $map['a.is_not_push']=$is_not_push;
        }

        if($is_follow!=''){
            $map['b.is_follow']=$is_follow;
        }

        if(!empty($pstatus)){
            if(count($pstatus)==1&&$pstatus[0]==0){

            }else{
                $map['b.progress_status']=['in',$pstatus];
            }
        }

        if(!empty($mer_name)){
            $mArr=model('Merchant')->where('mer_name','like','%'.$mer_name.'%')->column('id');
            if($mArr){
                $map['b.mer_id']=['in',$mArr];
            }else{
                $map['a.id']=0;
            }
        }
        //模糊查询城市
        if(!empty($cityname)){
            $cityIdArr=Db::name('city')->field('id,type,pid')->where('name','like',$cityname."%")->where('type',2)->find();
            if($cityIdArr){
                $map['a.city']=$cityIdArr['pid'].'-'.$cityIdArr['id'];
            }else{
                $map['a.city']=0;
            }
        }
        if(!empty($ac_name)){
            $adv_idArr=model('Account')->where('acc_name','like','%'.$ac_name.'%')->column('adv_id');
            if(!empty($adv_idArr)){
                $map['a.adv_id']=['in',$adv_idArr];
            }else{
                $map['a.adv_id']=0;
            }
        }


        if($this->group_id==7){
            $accIdArr=model('Account')->where('bind_youhua',$this->uid)->column('id');
            if(empty($accIdArr)){
                $map['a.account_id']=0;
            }else{
                $map['a.account_id']=['in',$accIdArr];
            }
        }

        switch ($sortBy){
            case 1:
                $orderBy='price asc';
                break;
            case 2:
                $orderBy='price desc';
                break;
            case 3:
                $orderBy='true_price asc';
                break;
            case 4:
                $orderBy='true_price desc';
                break;
            case 5:
                $orderBy='xz_price asc';
                break;
            case 6:
                $orderBy='xz_price desc';
                break;
            case 7:
                $orderBy='xz_true_price asc';
                break;
            case 8:
                $orderBy='xz_true_price desc';
                break;
            case 9:
                $orderBy='xz_price2 asc';
                break;
            case 10:
                $orderBy='xz_price2 desc';
                break;
            case 11:
                $orderBy='xz_true_price2 asc';
                break;
            case 12:
                $orderBy='xz_true_price2 desc';
                break;
            default:
                $orderBy='id desc';

        }

        // 查询条件end

        $channels = $this->getChannelArray();
//        $products = model('Product')->getListByMap();
        $productAll =Db::name('product')->column('name','id');
//        $products = model('Product')->where('status',1)->column('name','id');

//        $merchants = model('Merchant')->getListByMap([],'','',false);

        if(empty($num)||$num<2){
            $infosRe = model('Clue')->field('phone,count(id) cnum')->group('phone')->having('cnum >= 2')->select();
        }else{
            $infosRe = model('Clue')->field('phone,count(id) cnum')->group('phone')->having('cnum >='.$num)->select();
            if($infosRe){
                $map['a.phone']=['in',array_column($infosRe,'phone')];
            }

        }

//        $statusArr=Db::name('clue_progress_status')->order('sort desc')->select();
//        $statusList=array_column($statusArr,'name','id');
        $endStatus=[];
//        foreach ($statusArr as $v){
//            if($v['status']==1&&empty($v['delete_time'])){
//                $endStatus[]=['id'=>$v['id'],'name'=>$v['name']];
//            }
//        }

//        $total=model('Clue')->alias('a')->field('sum(a.price) price,sum(a.true_price) true_price,sum(a.xz_price) xz_price,sum(a.xz_true_price) xz_true_price,sum(a.xz_price2) xz_price2,sum(a.xz_true_price2) xz_true_price2')
//            ->join('clue_log b','a.id=b.clue_id','LEFT')
//            ->join('merchant c','c.id=b.mer_id','LEFT')
//            ->where($map)
//            ->find();
//        $price=!empty($total['price'])?$total['price']:0;
//        $true_price=!empty($total['true_price'])?$total['true_price']:0;
//        $xz_price=!empty($total['xz_price'])?$total['xz_price']:0;
//        $xz_true_price=!empty($total['xz_true_price'])?$total['xz_true_price']:0;
//        $xz_price2=!empty($total['xz_price2'])?$total['xz_price2']:0;
//        $xz_true_price2=!empty($total['xz_true_price2'])?$total['xz_true_price2']:0;


        $infos = model('Clue')->alias('a')->field('a.*,c.mer_name,c.mer_desc,c.username,c.phone mphone,b.push_type,show_city,is_find,b.city push_city,b.progress_status,b.push_channel')
            ->join('clue_log b','a.id=b.clue_id','LEFT')
            ->join('merchant c','c.id=b.mer_id','LEFT')
            ->order($orderBy)
            ->where($map)
            ->select();

//        dump($map);
//        dump(count($infos));
//        dump($infos);die;
//            ->getInfosByMap($map, '', false);

        $export=[];

        foreach ($infos as $k=>$v){

            if(!empty($v['progress_status'])){
                $infos[$k]['progress_status']='状态：'.$statusList[$v['progress_status']];
            }else{
                $infos[$k]['progress_status']='';
            }

            $infos[$k]['re_num']='';
            foreach ($infosRe as $val){
                if($v['phone']==$val['phone']){
                    $infos[$k]['re_num']=$val['cnum'];
                }
            }

            $infos[$k]['product_name']=empty($v['pro_id'])?'未知':$productAll[$v['pro_id']];

            $city1=$v['city'];
            $city2=$v['clue_city'];
            if($v['city'] != ''){
                $ids = explode('-',$v['city']);
                $cityNum=count($ids);
                if($cityNum==1){
                    $infos[$k]['city'] = $this->getCityName($ids[0]);
                }elseif ($cityNum==2){
                    $prov = $this->getCityName($ids[0]);
                    $city = $this->getCityName($ids[1]);
                    if($prov == $city){
                        $infos[$k]['city'] = $prov;
                    }else{
                        $infos[$k]['city'] = $prov.'-'.$city;
                    }
                }
            }

            if($v['clue_city'] != ''){
                $ids = explode('-',$v['clue_city']);
                $cityNum=count($ids);
                if($cityNum==1){
                    $infos[$k]['clue_city'] = $this->getCityName($ids[0]);
                }elseif ($cityNum==2){
                    $prov = $this->getCityName($ids[0]);
                    $city = $this->getCityName($ids[1]);
                    if($prov == $city){
                        $infos[$k]['clue_city'] = $prov;
                    }else{
                        $infos[$k]['clue_city'] = $prov.'-'.$city;
                    }
                }
            }

            if($v['push_city']==$city1){
                $v['push_city']= $infos[$k]['city'];
            }elseif ($v['push_city']==$city2){
                $v['push_city']= $infos[$k]['clue_city'];
            }else{
                $ids = explode('-',$v['push_city']);
                $cityNum=count($ids);
                if($cityNum==1){
                    $infos[$k]['push_city'] = $this->getCityName($ids[0]);
                }elseif ($cityNum==2){
                    $prov = $this->getCityName($ids[0]);
                    $city = $this->getCityName($ids[1]);
                    if($prov == $city){
                        $infos[$k]['push_city'] = $prov;
                    }else{
                        $infos[$k]['push_city'] = $prov.'-'.$city;
                    }
                }
            }


            if($v['push_time']){
                $infos[$k]['push_time'] = date('Y-m-d H:i:s',$v['push_time']);
            }

            $infos[$k]['acc_name'] = '手动添加的线索';
            $infos[$k]['acc_desc'] = '手动添加';
            $infos[$k]['channel_name'] = '后台系统';
            if($v['adv_id'] != ''){
                $account = Db::name('account')->where('adv_id','=',$v['adv_id'])->find();
                if($account){
                    $infos[$k]['acc_name'] = $account['acc_name'];
                    $infos[$k]['acc_desc'] = $account['acc_desc'];
                    $infos[$k]['channel_name'] = $channels[$account['channel_id']];
                }else{
                    $infos[$k]['acc_name'] = '未知账号';
                    $infos[$k]['acc_desc'] = '';
                    $infos[$k]['channel_name'] = $channels[$v['type']];
                }
            }
            if(empty($v['remark'])){
                $infos[$k]['remark_data']=[];
            }else{
                $remark=json_decode($v['remark'],true);
                if (is_array($remark)){
                    $remarkArr=[];
                    $keys=array_keys($remark);
                    $b=false;//默认索引
                    //判断关联数组还是索引数组
                    foreach($keys as $value){
                        if(!is_int($value)){
                            $b=true;
                            break;
                        }
                    }
                    //是关联数组
                    if($b){
                        foreach ($remark as $kk=>$vv){
                            if($kk=='城市'){
                            }else{
                                $remarkArr[]=$kk.'：'.$vv;
                            }
                        }
                    }else{
                        foreach ($remark as $vv){
                            if($v['type']==1){
                                if($vv['name']=='城市'){
                                }else{
                                    $remarkArr[]=$vv['name'].'：'.$vv['value'];
                                }
                            }else{
                                if(isset($vv['name'])&&isset($vv['value'])){
                                    $remarkArr[]=$vv['name'].'：'.$vv['value'];
                                }else{
                                    $remarkArr[]=json_encode($vv,JSON_UNESCAPED_UNICODE);
                                }
                            }
                        }
                    }
                }else{
                    $remarkArr=[];
                    $remarkArr[]=$v['remark'];

                }
                $infos[$k]['remark_data']=$remarkArr;
            }

            $export[]=[
                'id'=>$v['id'],
                'channel_name'=>$v['channel_name'],
                'product_name'=>$v['product_name'],
                'adv_id'=>$v['adv_id'],
                'acc_name'=>$v['acc_name'],

                'username'=>$v['username'],
                'mer_name'=>$v['mer_name'],


                'clue_name'=>$v['clue_name'],
                'phone'=>$v['phone'],
                'city'=>$v['city'],

                'price'=>$v['price'],
                'true_price'=>$v['true_price'],
                'xz_price'=>$v['xz_price'],
                'xz_true_price'=>$v['xz_true_price'],
                'xz_price2'=>$v['xz_price2'],
                'xz_true_price2'=>$v['xz_true_price2'],

                'create_time'=>$v['create_time'],
                'push_time'=>$v['push_time'],
            ];
        }


        if(empty($export)){
            echo '无记录导出';
            die;
        }

        $newExcel = new Spreadsheet();
//获取当前操作sheet的对象
        $objSheet = $newExcel->getActiveSheet();
        $date = date('Ymd',time());
        $name = '线索成本明细';
        $objSheet->setTitle($name);//设置当前sheet的标题
//设置表头


        $objSheet->setCellValue('A1', 'ID')
            ->setCellValue('B1', '渠道')
            ->setCellValue('C1', '产品')
            ->setCellValue('D1', '账户ID')
            ->setCellValue('E1', '账户名称')
            ->setCellValue('F1', '商户账号')
            ->setCellValue('G1', '账户名称')
            ->setCellValue('H1', '名称')
            ->setCellValue('I1', '电话')
            ->setCellValue('J1', '城市')
            ->setCellValue('K1', '账户币成本')
            ->setCellValue('L1', '真实币成本')
            ->setCellValue('M1', '账户币修正成本1')
            ->setCellValue('N1', '真实币修正成本1')
            ->setCellValue('O1', '账户币修正成本2')
            ->setCellValue('P1', '真实币修正成本2')
            ->setCellValue('Q1', '创建时间')
            ->setCellValue('R1', '推送时间')
        ;

        $objSheet->getColumnDimension('A')->setWidth(10);//ID
        $objSheet->getColumnDimension('B')->setWidth(10);
        $objSheet->getColumnDimension('C')->setWidth(10);
        $objSheet->getColumnDimension('D')->setWidth(15);//账户ID
        $objSheet->getColumnDimension('E')->setWidth(20);
        $objSheet->getColumnDimension('F')->setWidth(20);//账户ID
        $objSheet->getColumnDimension('G')->setWidth(20);
        $objSheet->getColumnDimension('H')->setWidth(15);//名称
        $objSheet->getColumnDimension('I')->setWidth(15);
        $objSheet->getColumnDimension('J')->setWidth(15);
        $objSheet->getColumnDimension('K')->setWidth(15);//成本
        $objSheet->getColumnDimension('L')->setWidth(15);
        $objSheet->getColumnDimension('M')->setWidth(15);
        $objSheet->getColumnDimension('N')->setWidth(15);
        $objSheet->getColumnDimension('O')->setWidth(15);
        $objSheet->getColumnDimension('P')->setWidth(15);
        $objSheet->getColumnDimension('Q')->setWidth(20);
        $objSheet->getColumnDimension('R')->setWidth(20);

        $info = $export;
        $dataCount = count($info);
        $k = 1;
        if($dataCount == 0){
            exit;
        }else {
            for ($i = 0; $i < $dataCount; $i++) {
                $k = $k + 1;
                $objSheet->setCellValue('A' . $k, $info[$i]['id'])
                    ->setCellValue('B' . $k, $info[$i]['channel_name'])
                    ->setCellValue('C' . $k, $info[$i]['product_name'])
                    ->setCellValue('D' . $k, $info[$i]['adv_id'])
                    ->setCellValue('E' . $k, $info[$i]['acc_name'])
                    ->setCellValue('F' . $k, $info[$i]['username'])
                    ->setCellValue('G' . $k, $info[$i]['mer_name'])
                    ->setCellValue('H' . $k, $info[$i]['clue_name'])
                    ->setCellValue('I' . $k, $info[$i]['phone'])
                    ->setCellValue('J' . $k, $info[$i]['city'])
                    ->setCellValue('K' . $k, $info[$i]['price'])
                    ->setCellValue('L' . $k, $info[$i]['true_price'])
                    ->setCellValue('M' . $k, $info[$i]['xz_price'])
                    ->setCellValue('N' . $k, $info[$i]['xz_true_price'])
                    ->setCellValue('O' . $k, $info[$i]['xz_price2'])
                    ->setCellValue('P' . $k, $info[$i]['xz_true_price2'])
                    ->setCellValue('Q' . $k, $info[$i]['create_time'])
                    ->setCellValue('R' . $k, $info[$i]['push_time']);

            }
        }


        $filename = date('Y-m-d').$name.'导出';
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename='.$filename.'.xlsx');
        header('Cache-Control: max-age=0');
//
        $write = IOFactory::createWriter($newExcel, 'Xlsx');
        $write->save('php://output');
    }

    public function clueCostDetails()
    {

        // 查询条件start
        $clue_id = input('clue_id','');
        $clue_name = input('clue_name','');
        $phone = input('phone','');
        $source = input('source','0');
        $status = input('status/d',99);
        $times = input('times','');
        $times2 = input('times2','');
        $pro_id = input('pro_id','');
        $city = input('city','');
        $num = input('num','');
        $err_msg = input('err_msg','');
        $cityname = input('cityname','');
        $ac_name = input('ac_name','');
        $adv_id = input('adv_id','');
        $mer_name = input('mer_name','');
        $channel_id = input('channel_id','');
        $pstatus = input('pstatus/a','');
        $is_find = input('is_find','');
        $is_not_push = input('is_not_push','');
        $is_follow = input('is_follow','');

        $sortBy=input('orderBy','');
        $youhua_id = input('youhua_id','');
        $pay_type = input('pay_type','');
        $stat_type = input('stat_type',1);
        $week = input('week','');


        $waste_where = [];
        $map_clue = [];
        $map = [];
        $map_zero_clue = [];
        if($clue_id){
            $map['a.clue_id']=$clue_id;
        }
        if($clue_name != ''){
            $map['a.clue_name'] = ['like','%'.$clue_name.'%'];
        }
        if($phone != 0){
            $map['a.phone'] = $phone;
        }
//        if($source != '0'){
//            $map['source'] = $source;
//        }
        if ($stat_type == 1) { // 按单日计算
            if($times != ''){
                $time_arr = explode(' - ',$times);
                $map['a.create_time'] = ['between',[strtotime($time_arr[0]),strtotime($time_arr[1])]];
                $waste_where['time'] = ['between',[date("Y-m-d", strtotime($time_arr[0])), date("Y-m-d", strtotime($time_arr[1]))]];
                $map_clue['create_time'] = ['between',[strtotime($time_arr[0]),strtotime($time_arr[1])]];
                $map_zero_clue['clue_time'] = ['between',[strtotime($time_arr[0]),strtotime($time_arr[1])]];
            }
        } elseif ($stat_type == 2) { // 按周期7天计算
            if (!empty($week)) {
                $range = getWeekRange($week);
                $time_arr = [$range['start'], date("Y-m-d H:i:s", strtotime($range['end'])+86399)];
                $map['a.create_time'] = ['between',[strtotime($time_arr[0]),strtotime($time_arr[1])]];
                $waste_where['time'] = ['between',[date("Y-m-d", strtotime($time_arr[0])), date("Y-m-d", strtotime($time_arr[1]))]];
                $map_clue['create_time'] = ['between',[strtotime($time_arr[0]),strtotime($time_arr[1])]];
                $map_zero_clue['clue_time'] = ['between',[strtotime($time_arr[0]),strtotime($time_arr[1])]];
            }
        }

        if($times2 != ''){
            $time_arr = explode(' - ',$times2);
            $map['b.create_time'] = ['between',[strtotime($time_arr[0]),strtotime($time_arr[1])]];
        }
        if($status!=99){
            $map['a.status']=$status;
        }
        if($pro_id!=''){
            $map['a.pro_id']=$pro_id;
            $waste_where['pro_id'] = $pro_id;
            $map_clue['pro_id'] = $pro_id;
        }
        if(!empty($city)){
            $map['a.city']=$city;
        }
        if(!empty($err_msg)){
            $map['a.err_msg']=['like','%'.$err_msg.'%'];
        }

        if($adv_id){
            $map['a.adv_id']=$adv_id;
            $account=Db::name('account')->where('id',$adv_id)->find();
            $waste_where['account_id'] = $account['id'];
        }
        if($channel_id){
            $map['a.type']=$channel_id;
        }

        if($is_find!=''){
            $map['b.is_find']=$is_find;
        }
        if($is_not_push!=''){
            $map['a.is_not_push']=$is_not_push;
        }

        if($is_follow!=''){
            $map['b.is_follow']=$is_follow;
        }

        if(!empty($pstatus)){
            if(count($pstatus)==1&&$pstatus[0]==0){

            }else{
                $map['b.progress_status']=['in',$pstatus];
            }
        }

        if(!empty($mer_name)){
            $mArr=model('Merchant')->where('mer_name','like','%'.$mer_name.'%')->column('id');
            if($mArr){
                $map['b.mer_id']=['in',$mArr];
            }else{
                $map['a.id']=0;
            }
        }
        //模糊查询城市
        if(!empty($cityname)){
            $cityIdArr=Db::name('city')->field('id,type,pid')->where('name','like',$cityname."%")->where('type',2)->find();
            if($cityIdArr){
                $map['a.city']=$cityIdArr['pid'].'-'.$cityIdArr['id'];
                $waste_where['city'] = $cityIdArr['pid'].'-'.$cityIdArr['id'];
                $map_clue['city'] = $cityIdArr['pid'].'-'.$cityIdArr['id'];
            }else{
                $map['a.city']=0;
                $waste_where['city'] = 0;
                $map_clue['city'] = 0;
            }
        }
        if(!empty($ac_name)){
            $adv_idArr=model('Account')->where('acc_name','like','%'.$ac_name.'%')->column('adv_id');
            if(!empty($adv_idArr)){
                $map['a.adv_id']=['in',$adv_idArr];
                $map_clue['adv_id'] = ['in',$adv_idArr];
                $account_arr = Db::name('account')->where('acc_name','like','%'.$ac_name.'%')->column('id');
                if (!empty($account_arr)) {
                    $waste_where['account_id'] = ['in', $account_arr];
                }
            }else{
                $map['a.adv_id']=0;
                $waste_where['account_id'] = 0;
                $map_clue['adv_id'] = 0;
            }
        }


        if($this->group_id==7){
            $accIdArr=model('Account')->where('bind_youhua',$this->uid)->column('id');
            if(empty($accIdArr)){
                $map['a.account_id']=0;
                $waste_where['account_id'] = 0;
                $map_clue['account_id'] = 0;
            }else{
                $map['a.account_id']=['in',$accIdArr];
                $waste_where['account_id'] = ['in',$accIdArr];
                $map_clue['account_id'] = ['in',$accIdArr];
            }
        }

        switch ($sortBy){
            case 1:
                $orderBy='price asc';
                break;
            case 2:
                $orderBy='price desc';
                break;
            case 3:
                $orderBy='true_price asc';
                break;
            case 4:
                $orderBy='true_price desc';
                break;
            case 5:
                $orderBy='xz_price asc';
                break;
            case 6:
                $orderBy='xz_price desc';
                break;
            case 7:
                $orderBy='xz_true_price asc';
                break;
            case 8:
                $orderBy='xz_true_price desc';
                break;
            case 9:
                $orderBy='xz_price2 asc';
                break;
            case 10:
                $orderBy='xz_price2 desc';
                break;
            case 11:
                $orderBy='xz_true_price2 asc';
                break;
            case 12:
                $orderBy='xz_true_price2 desc';
                break;
            default:
                $orderBy='id desc';

        }

        //优化师
        if($youhua_id!=''){
            $map['act.bind_youhua']=$youhua_id;
        }

        // 查询 先付费的修正成本3
        if ($pay_type == 1) {
            $map['b.price'] = ['>', 0];

        } elseif ($pay_type == 2) {
            // 查询先付费的 成本
            $map['b.price'] = ['<=', 0];
        }

        // 查询条件end

        $channels = $this->getChannelArray();
//        $products = model('Product')->getListByMap();
        $productAll =Db::name('product')->column('name','id');
        $products = model('Product')->where('status',1)->column('name','id');

        $merchants = model('Merchant')->getListByMap([],'','',false);

        if(empty($num)||$num<2){
            $infosRe = model('Clue')->field('phone,count(id) cnum')->group('phone')->having('cnum >= 2')->select();
        }else{
            $infosRe = model('Clue')->field('phone,count(id) cnum')->group('phone')->having('cnum >='.$num)->select();
            if($infosRe){
                $map['a.phone']=['in',array_column($infosRe,'phone')];
            }
        }

        $statusArr=Db::name('clue_progress_status')->order('sort desc')->select();
        $statusList=array_column($statusArr,'name','id');
        $endStatus=[];
        foreach ($statusArr as $v){
            if($v['status']==1&&empty($v['delete_time'])){
                $endStatus[]=['id'=>$v['id'],'name'=>$v['name']];
            }
        }

        $total=model('Clue')->alias('a')
            ->field('sum(a.price) price,sum(a.true_price) true_price,sum(a.xz_price) xz_price,sum(a.xz_true_price) xz_true_price,sum(a.xz_price2) xz_price2,sum(a.xz_true_price2) xz_true_price2,sum(a.xz_price3) xz_price3,sum(a.xz_true_price3) xz_true_price3,sum(a.xz_price4) xz_price4,sum(a.xz_true_price4) xz_true_price4,sum(a.week_price) week_price,sum(a.week_true_price) week_true_price')
            ->join('clue_log b','a.id=b.clue_id','LEFT')
            ->join('merchant c','c.id=b.mer_id','LEFT')
            ->join('account act','a.adv_id=act.adv_id','LEFT')
            ->where($map)
            ->find();

        $price=!empty($total['price'])?$total['price']:0;
        $true_price=!empty($total['true_price'])?$total['true_price']:0;
        $xz_price=!empty($total['xz_price'])?$total['xz_price']:0;
        $xz_true_price=!empty($total['xz_true_price'])?$total['xz_true_price']:0;
        $xz_price2=!empty($total['xz_price2'])?$total['xz_price2']:0;
        $xz_true_price2=!empty($total['xz_true_price2'])?$total['xz_true_price2']:0;
        $xz_price3=!empty($total['xz_price3'])?$total['xz_price3']:0;
        $xz_true_price3=!empty($total['xz_true_price3'])?$total['xz_true_price3']:0;
        $xz_price4=!empty($total['xz_price4'])?$total['xz_price4']:0;
        $xz_true_price4=!empty($total['xz_true_price4'])?$total['xz_true_price4']:0;
        $week_price=!empty($total['week_price'])?$total['week_price']:0;
        $week_true_price=!empty($total['week_true_price'])?$total['week_true_price']:0;

        $infos = model('Clue')->alias('a')->field('a.*,c.mer_name,c.mer_desc,c.username,c.phone mphone,b.push_type,show_city,is_find,b.city push_city,b.progress_status,b.push_channel')
            ->join('clue_log b','a.id=b.clue_id','LEFT')
            ->join('merchant c','c.id=b.mer_id','LEFT')
            ->join('account act','a.adv_id=act.adv_id','LEFT')
            ->order($orderBy)
            ->where($map)
            ->paginate();
//        dump($infos);die;
//            ->getInfosByMap($map, '', false);

        foreach ($infos as $k=>$v){

            if(!empty($v['progress_status'])){
                $infos[$k]['progress_status']='状态：'.$statusList[$v['progress_status']];
            }else{
                $infos[$k]['progress_status']='';
            }

            $infos[$k]['re_num']='';
            foreach ($infosRe as $val){
                if($v['phone']==$val['phone']){
                    $infos[$k]['re_num']=$val['cnum'];
                }
            }

            $infos[$k]['product_name']=empty($v['pro_id'])?'未知':$productAll[$v['pro_id']];

            $city1=$v['city'];
            $city2=$v['clue_city'];
            if($v['city'] != ''){
                $ids = explode('-',$v['city']);
                $cityNum=count($ids);
                if($cityNum==1){
                    $infos[$k]['city'] = $this->getCityName($ids[0]);
                }elseif ($cityNum==2){
                    $prov = $this->getCityName($ids[0]);
                    $city = $this->getCityName($ids[1]);
                    if($prov == $city){
                        $infos[$k]['city'] = $prov;
                    }else{
                        $infos[$k]['city'] = $prov.'-'.$city;
                    }
                }
            }

            if($v['clue_city'] != ''){
                $ids = explode('-',$v['clue_city']);
                $cityNum=count($ids);
                if($cityNum==1){
                    $infos[$k]['clue_city'] = $this->getCityName($ids[0]);
                }elseif ($cityNum==2){
                    $prov = $this->getCityName($ids[0]);
                    $city = $this->getCityName($ids[1]);
                    if($prov == $city){
                        $infos[$k]['clue_city'] = $prov;
                    }else{
                        $infos[$k]['clue_city'] = $prov.'-'.$city;
                    }
                }
            }

            if($v['push_city']==$city1){
                $v['push_city']= $infos[$k]['city'];
            }elseif ($v['push_city']==$city2){
                $v['push_city']= $infos[$k]['clue_city'];
            }else{
                $ids = explode('-',$v['push_city']);
                $cityNum=count($ids);
                if($cityNum==1){
                    $infos[$k]['push_city'] = $this->getCityName($ids[0]);
                }elseif ($cityNum==2){
                    $prov = $this->getCityName($ids[0]);
                    $city = $this->getCityName($ids[1]);
                    if($prov == $city){
                        $infos[$k]['push_city'] = $prov;
                    }else{
                        $infos[$k]['push_city'] = $prov.'-'.$city;
                    }
                }
            }


            if($v['push_time']){
                $infos[$k]['push_time'] = date('Y-m-d H:i:s',$v['push_time']);
            }

            $infos[$k]['acc_name'] = '手动添加的线索';
            $infos[$k]['acc_desc'] = '手动添加';
            $infos[$k]['channel_name'] = '后台系统';
            if($v['adv_id'] != ''){
                $account = Db::name('account')->where('adv_id','=',$v['adv_id'])->find();
                if($account){
                    $infos[$k]['acc_name'] = $account['acc_name'];
                    $infos[$k]['acc_desc'] = $account['acc_desc'];
                    $infos[$k]['channel_name'] = $channels[$account['channel_id']];
                }else{
                    $infos[$k]['acc_name'] = '未知账号';
                    $infos[$k]['acc_desc'] = '';
                    $infos[$k]['channel_name'] = $channels[$v['type']];
                }
            }
            if(empty($v['remark'])){
                $infos[$k]['remark_data']=[];
            }else{
                $remark=json_decode($v['remark'],true);
                if (is_array($remark)){
                    $remarkArr=[];
                    $keys=array_keys($remark);
                    $b=false;//默认索引
                    //判断关联数组还是索引数组
                    foreach($keys as $value){
                        if(!is_int($value)){
                            $b=true;
                            break;
                        }
                    }
                    //是关联数组
                    if($b){
                        foreach ($remark as $kk=>$vv){
                            if($kk=='城市'){
                            }else{
                                $remarkArr[]=$kk.'：'.$vv;
                            }
                        }
                    }else{
                        foreach ($remark as $vv){
                            if($v['type']==1){
                                if($vv['name']=='城市'){
                                }else{
                                    $remarkArr[]=$vv['name'].'：'.$vv['value'];
                                }
                            }else{
                                if(isset($vv['name'])&&isset($vv['value'])){
                                    $remarkArr[]=$vv['name'].'：'.$vv['value'];
                                }else{
                                    $remarkArr[]=json_encode($vv,JSON_UNESCAPED_UNICODE);
                                }
                            }
                        }
                    }
                }else{
                    $remarkArr=[];
                    $remarkArr[]=$v['remark'];

                }
                $infos[$k]['remark_data']=$remarkArr;
            }

//            $infos[$k]['progress']=model('ClueProgress')->where('clue_id',$v['id'])->order('id desc')->select();
//
//            $infos[$k]['error_log']=[];
//            if($v['status']==0){
//                $infos[$k]['error_log']=model('ClueErrorLog')->where('clue_id',$v['clue_id'])->order('id desc')->select();
//            }

        }

//        $sources = Db::name('clue')->field('source')->where('source','<>','')->group('source')->select();

        $province = Db::name('city')->where(['pid'=>1])->select();
//        $this->assign('province',$province);
//        dump($infos);die;

//        dump($infos->total());die;

        if(is_array($pstatus)){
            $pstatus=implode(',',$pstatus);
        }else{
            $pstatus=0;
        }

        $youhua = model('AuthGroupAccess')->alias('a')
            ->field('a.*,b.phone,b.realname')
            ->join('admin b','a.uid=b.id')
            ->where(function ($q){
                $q->where('a.group_id',7);
            })
//        ->where('a.group_id',4)
            ->where('b.delete_time',NULL)->select();

        return $this->fetch('',[
            'infos' => $infos,
            'clue_name' => $clue_name,
            'phone' => $phone,
            'source' => $source,
            'times' => $times,
            'times2' => $times2,
            'sources' => [],
            'province' => $province,
            'status' => $status,
            'pro_id' => $pro_id,
            'products' => $products,
            'num' => $num,
            'err_msg' => $err_msg,
            'cityname' => $cityname,
            'ac_name' => $ac_name,
            'adv_id' => $adv_id,
            'mer_name' => $mer_name,
            'merchants' => $merchants,
            'channels' => $channels,
            'channel_id' => $channel_id,
            'clue_id' => $clue_id,
            'endStatus' => $endStatus,
            'pstatus' => $pstatus,
            'is_find' => $is_find,
            'is_not_push' => $is_not_push,
            'is_follow' => $is_follow,
            'group_id'=>$this->group_id,
            'price'=>$price,
            'true_price'=>$true_price,
            'xz_price'=>$xz_price,
            'xz_true_price'=>$xz_true_price,
            'xz_price2'=>$xz_price2,
            'xz_true_price2'=>$xz_true_price2,
            'xz_price3'=>$xz_price3,
            'xz_true_price3'=>$xz_true_price3,
            'xz_price4'=>$xz_price4,
            'xz_true_price4'=>$xz_true_price4,
            'week_price'=>$week_price,
            'week_true_price'=>$week_true_price,
            'sortBy'=>$sortBy,
            'youhua' => $youhua,
            'youhua_id' => $youhua_id,
            'pay_type' => $pay_type,
            'stat_type' => $stat_type,
            'week' => $week
            //'waste_cost_price' => $waste,
        ]);
    }

    public function saveProgress(){
        $cid = input('cid');//线索id
        $id = input('id');//记录id
        $content = input('content');//记录id
        if(empty($cid)){
            return self::showReturnCode(1011,'保存错误');
        }
        if(empty($content)){
            return self::showReturnCode(1011,'记录内容不能为空');
        }


        $tabName='ClueLog';
        $tabName2='ClueProgress';

        $minfo=model($tabName)->where('clue_id',$cid)->find();

//        dump($minfo);die;

//        if(!empty($id)){
//            $save_data['id']=$id;
//        }

        $save_data['content']=$content;
        $save_data['source']=3;


        if(isset($id) && $id){
            $result =model($tabName2)->where('id',$id)->update($save_data);
            $msg = '修改成功';
        }else{
            $save_data['clue_id']=$minfo['clue_id'];
            $save_data['clue_log_id']=$minfo['id'];
            $result =model($tabName2)->save($save_data);
            model($tabName)->where('id',$cid)->update(['is_follow'=>1]);
            $msg = '添加成功';
        }


//        $result =model($tabName2)->save($save_data);
        if($result){
            return self::showReturnCode(1001,$msg);
        }else{
            return self::showReturnCode(1011,'保存失败');
        }

    }

    //删除跟进记录
    public function delProgress(){
        $id = input('id');//记录id
        if(empty($id)){
            return self::showReturnCode(1011,'ID错误');
        }

        $tabName='ClueLog';
        $tabName2='ClueProgress';

//        $log=model($tabName2)->where('id',$id)->find();
//        if(empty($log)){
//            return json(['code'=>400,'msg'=>'记录获取失败']);
//        }
//        $minfo=model($tabName)->where('id',$log['clue_log_id'])->find();
//        $aid=session('aid');
//        if(empty($minfo)||$minfo['mer_id']!=$aid){
//            return json(['code'=>400,'msg'=>'非法请求']);
//        }

        $result =model($tabName2)->destroy($id);
        if($result){
            return self::showReturnCode(1001,'删除成功');
        }else{
            return self::showReturnCode(1011,'删除失败');
        }
    }

    public function getRegion(){
        $map['pid']=input('pid');
        $map['type']=input('type');
        $list=Db::name('city')->where($map)->select();
        return self::showJsonReturnCodeData('1001',$list,'');
    }

    public function getMerchantPush(){
        $map['mer_id']=input('pid');
        $list=Db::name('push')->where("delete_time IS NULL")->where($map)->select();
        foreach ($list as &$v){
            $ids = explode('-',$v['city']);
            $prov = $this->getCityName($ids[0]);
            $city = $this->getCityName($ids[1]);
            if($prov == $city){
                $v['dcity'] = $prov;
            }else{
                $v['dcity'] = $prov.'-'.$city;
            }
            if($v['charge_type']==1){
                $v['dcharge_type']='按服务收费';
            }elseif ($v['charge_type']==2){
                $v['dcharge_type']='按单价收费';
            }

        }
        return self::showJsonReturnCodeData('1001',$list,'');
    }


    public function edit()
    {
        $id = input('id');
        if(!$id) return self::showReturnCode(1002,'id 错误');
        $info = model('Clue')->getInfoByMap(['id'=>$id]);
        if(!empty($info['city'])){
            $ids = explode('-',$info['city']);
            $info['prov'] = $ids[0];
            $info['city'] = $ids[1];
            $info['city_name'] = $this->getCityName($ids[1]);
        }else{
            $info['prov'] = 0;
            $info['city'] = 0;
            $info['city_name'] = '';
        }
        return self::showJsonReturnCodeData('1001',$info,'');
    }

    public function edit2()
    {
        $id = input('id');
        if(!$id) return self::showReturnCode(1002,'id 错误');
        $merchant=model('Merchant')->field('id,mer_name,phone,username')->where('status',1)->select();
        $info = model('Clue')->getInfoByMap(['id'=>$id]);
        $info['merchant']=$merchant;
        if(!empty($info['city'])){
            $ids = explode('-',$info['city']);
            $info['prov'] = $ids[0];
            $info['city'] = $ids[1];
            $info['city_name'] = $this->getCityName($ids[1]);
        }else{
            $info['prov'] = 0;
            $info['city'] = 0;
            $info['city_name'] = '';
        }
        return self::showJsonReturnCodeData('1001',$info,'');
    }

    public function edit3()
    {

        $merchant=model('Merchant')->field('id,mer_name,phone,username')->where('status',1)->select();
        $info['merchant']=$merchant;
        if(!empty($info['city'])){
            $ids = explode('-',$info['city']);
            $info['prov'] = $ids[0];
            $info['city'] = $ids[1];
            $info['city_name'] = $this->getCityName($ids[1]);
        }else{
            $info['prov'] = 0;
            $info['city'] = 0;
            $info['city_name'] = '';
        }
        return self::showJsonReturnCodeData('1001',$info,'');
    }

    public function save()
    {
        if(request()->isAjax()){
            try{

                $id = input('post.id');
                $save_data = input('post.');

                if(isset($id) && $id){
                    $save_data['id'] = $id;
                }else{
                    unset($save_data['id']);
                }

                if($save_data['province'] != ''){
                    $save_data['city'] = $save_data['province'].'-'.$save_data['city'];
                }else{
                    $save_data['city'] = '';
                }

                if (!empty($save_data['remark'])) {
                    $save_data['remark'] = htmlspecialchars_decode($save_data['remark']);
                    $remark = json_decode($save_data['remark'], true);
                    if (empty($remark)) {
                        unset($save_data['remark']);
                    }
                }

                $result = $this->editData(false,'','Clue',$save_data);
                if($result['code'] == 1001){
                    if(isset($id) && $id){
                        $result['msg'] = '修改线索成功';
                        $this->RecordSystemLog($this->uid,$this->behavior,'修改线索【'.$save_data['clue_name'].'】成功');
                    }else{
                        $result['msg'] = '添加线索成功';
                        $this->RecordSystemLog($this->uid,$this->behavior,'添加线索【'.$save_data['clue_name'].'】成功');
                    }
                }

                return $result;
            }catch (\Exception $e){
                Log::error($e->getMessage());
                return self::showReturnCode(1011,$e->getMessage());
            }
        }else{
            return self::showReturnCode(1002);
        }
    }

    public function savePro()
    {
        if(request()->isAjax()){
            try{

                $id = input('post.id');
                if(!$id){
                    return self::showReturnCode(1011,'id 错误');
                }
                $save_data = input('post.');

                if($save_data['pro_id'] == 0){
                    return self::showReturnCode(1011,'请选择产品');
                }

                $result = $this->editData(false,'','Clue',$save_data);
                if($result['code'] == 1001){
                    $result['msg'] = '编辑产品成功';
                    $this->RecordSystemLog($this->uid,$this->behavior,'【'.$id.'】编辑产品成功');
                }

                return $result;
            }catch (\Exception $e){
                Log::error($e->getMessage());
                return self::showReturnCode(1011,$e->getMessage());
            }
        }else{
            return self::showReturnCode(1002);
        }
    }

    //固定推送
    public function findPush(){
        if(request()->isAjax()){
            $id = input('post.id');
            $mid = input('post.merchant');
            $pid = input('post.mrule');
            $city = input('post.show_city');
            $pushChannel = input('post.push_channel');


            $merchant=Db::name('merchant')->find($mid);
            if(!$merchant){
                return $this->showReturnCode(1011,'商户获取失败');
            }
            $push=Db::name('push')->find($pid);
            if(!$push){
                return $this->showReturnCode(1011,'分发规则获取失败');
            }
            if($merchant['status']!=1){
                return $this->showReturnCode(1011,'该商户已禁用');
            }

            $success=0;
            $error=0;
            if(strpos($id, ',') !== false){
                $idArr=explode(',',$id);

                foreach ($idArr as $id){
                    $clue_info = Db::name('clue')->find($id);
                    if(!$clue_info){
                        return $this->showReturnCode(1011,'线索获取失败');
                    }
                    if(strpos($clue_info['clue_name'], '测试') !== false){
                        return $this->showReturnCode(1011,'测试线索不能推送！');
                    }
                    if(!empty($city)){
                        $clue_info['show_city']=$city;
                    }
                    if(!empty($pushChannel)){
                        $clue_info['push_channel']=$pushChannel;
                    }
                    $res=(new ClueModel())->sendMerchantClue($push,$clue_info,1);
                    if($res===true){
                        $success+=1;
                        $this->RecordSystemLog($this->uid,$this->behavior,'线索推送成功,操作ID: '.$id);
                        $sendPhone=$merchant['phone'];

                        if($merchant['is_send_phone']==1&&$sendPhone&&request()->domain()!=config('testdomain')){
                            $mobiles=$sendPhone;
                            $content='【'.config('database')['host_sms_name']."】提醒你有个线索查看！";
                            $extno='';
                            $sendtime='';
//                            MessageSend::send($mobiles,$extno,$content,$sendtime);
                            $sendRes=SmsMuSend::send($mobiles,$content);
                        }

                        //子商户推送
                        if($merchant['is_sub_mer']==1){
                            // 1.当前任务将由哪个类来负责处理。
                            // 当轮到该任务时，系统将生成一个该类的实例，并调用其 fire 方法
                            $jobHandlerClassName  = 'app\job\SubCluePush@fire';
                            // 2.当前任务归属的队列名称，如果为新队列，会自动创建
                            $jobQueueName     = "SubCluePush";

                            $jobData = ['mer_id'=>$merchant['id'],'clue_id'=>$clue_info['id']];
                            $isPushed = Queue::push($jobHandlerClassName, $jobData, $jobQueueName);
                        }
                    }else{
                        $error+=1;
                    }
                }

                return $this->showReturnCode(1001,'推送成功:'.$success.'条，推送失败'.$error.'条。');

            }else{
                $clue_info = Db::name('clue')->find($id);
                if(!$clue_info){
                    return $this->showReturnCode(1011,'线索获取失败');
                }
                if(strpos($clue_info['clue_name'], '测试') !== false){
                    return $this->showReturnCode(1011,'测试线索不能推送！');
                }
                if(!empty($city)){
                    $clue_info['show_city']=$city;
                }
                if(!empty($pushChannel)){
                    $clue_info['push_channel']=$pushChannel;
                }
                $res=(new ClueModel())->sendMerchantClue($push,$clue_info,1);
                if($res===true){
                    $this->RecordSystemLog($this->uid,$this->behavior,'线索推送成功,操作ID: '.$id);
                    $sendPhone=$merchant['phone'];
                    if($merchant['is_send_phone']==1&&$sendPhone&&request()->domain()!=config('testdomain')){
                        $mobiles=$sendPhone;
                        $content='【'.config('database')['host_sms_name']."】提醒你有个线索查看！";
                        $extno='';
                        $sendtime='';
//                        MessageSend::send($mobiles,$extno,$content,$sendtime);
                        $sendRes=SmsMuSend::send($mobiles,$content);
                    }

                    //子商户推送
                    if($merchant['is_sub_mer']==1){
                        // 1.当前任务将由哪个类来负责处理。
                        // 当轮到该任务时，系统将生成一个该类的实例，并调用其 fire 方法
                        $jobHandlerClassName  = 'app\job\SubCluePush@fire';
                        // 2.当前任务归属的队列名称，如果为新队列，会自动创建
                        $jobQueueName     = "SubCluePush";

                        $jobData = ['mer_id'=>$merchant['id'],'clue_id'=>$clue_info['id']];
                        $isPushed = Queue::push($jobHandlerClassName, $jobData, $jobQueueName);
                    }
                    return $this->showReturnCode(1001,'线索推送成功');
                }else{
                    return $this->showReturnCode(1011,'线索推送失败：'.$clue_info['clue_name'].$res);
                }
            }

        }else{
            return self::showReturnCode(1002);
        }
    }



    //随机推送
    public function status()
    {
        if($this->request->isAjax()){
            $id = input('post.id');
            // 手动推送线索
            $clue_info = model('Clue')->find($id);
            $push_res = (new ClueModel())->cluePush($clue_info,false);
            if($push_res['code'] == 200){
                $this->RecordSystemLog($this->uid,$this->behavior,'线索推送成功,操作ID: '.$id);
                return $this->showReturnCode(1001,$push_res['msg']);
            }else{
                return $this->showReturnCode(1009,$push_res['msg']);
            }

        }else{
            return $this->showReturnCode(1002);
        }
    }

    //随机推送
    public function statusAll()
    {
        if($this->request->isAjax()){
            $idArr = input('post.id/a');
            $success=0;
            $error=0;



            $jobHandlerClassName  = 'app\job\DayReClue@fire';
            // 2.当前任务归属的队列名称，如果为新队列，会自动创建
            $jobQueueName     = "DayReClue";

            $time2wait=mt_rand(15,20);
            foreach ($idArr as $id){
                // 手动推送线索
//                $clue_info = model('Clue')->find($id);
//                $push_res = (new ClueModel())->cluePush($clue_info);
                $jobData = ['id'=>$id];
                $isPushed = Queue::later($time2wait, $jobHandlerClassName, $jobData, $jobQueueName);
                $time2wait += mt_rand(15,20);

                if($isPushed){
                    $this->RecordSystemLog($this->uid,$this->behavior,'线索加入推送队列,操作ID: '.$id);
                    $success+=1;
//                    return $this->showReturnCode(1001,$push_res['msg']);
                }else{
                    $error+=1;
//                    return $this->showReturnCode(1009,$push_res['msg']);
                }
            }
            return $this->showReturnCode(1001,'提交成功:'.$success.'条，失败'.$error.'条。');
        }else{
            return $this->showReturnCode(1002);
        }
    }

    //线索需求
    public function clueDemand(){
        $province = input('province','');
        $orderb = input('orderb','');
        $status = input('status/d',1);
        $channel_id = input('channel_id/a',0);
        $account_id = input('account_id/a',0);
        $pro_id = input('pro_id/d',0);
        $type = input('type',2);
        $times = input('times',date('Y-m-d'));

        $map = [];

        $map1=[];
        $map2=[];
        $map3=[];
        $map4=[];
        $mapa=[];
        $map5=[];
        if(!empty($province)){
            $map['a.city']=['like',$province.'-'.'%'];
        }

        if($type==1){
//            $map['a.type']=$type;
            if(!empty($channel_id)){
                if(count($channel_id)==1&&$channel_id[0]==0){

                }else{
//                $map['a.channel_id']=['in',$channel_id];
//                $mapa='find_in_set(channel_id, "'.implode(',', $channel_id).'")';

                    $channelStr=[];
                    foreach ($channel_id as $v){
                        $channelStr[]='find_in_set("'.$v.'",channel_id)';
                    }
                    $mapa=implode(' or ',$channelStr);

                    $map1['type']=['in',$channel_id];
                    $map2['channel_id']=['in',$channel_id];
//                $map3['channel_id']=['in',$channel_id];
                    $map4['channel_id']=['in',$channel_id];
                }
            }
        }elseif($type==2){
//            $map['a.type']=$type;
            if(!empty($account_id)){
                if(count($account_id)==1&&$account_id[0]==0){

                }else{
//                $map['a.channel_id']=['in',$channel_id];
//                $mapa='find_in_set(channel_id, "'.implode(',', $channel_id).'")';

                    $channelStr=[];
                    foreach ($account_id as $v){
                        $channelStr[]='find_in_set("'.$v.'",account_id)';
                    }
                    $mapa=implode(' or ',$channelStr);

                    $map1['account_id']=['in',$account_id];
                    $map2['account_id']=['in',$account_id];
//                $map3['channel_id']=['in',$channel_id];
                    $map4['account_id']=['in',$account_id];
                }
            }
        }

        if(!empty($pro_id)){
            $map['a.pro_id']=$pro_id;
            $map1['pro_id']=$pro_id;
            $map2['pro_id']=$pro_id;
            $map3['pro_id']=$pro_id;
            $map4['pro_id']=$pro_id;
            $map5['pro_id']=$pro_id;
        }

//        if(in_array($this->group_id,[4,5])){
//            $map3['bind_aid|weihu_aid']=$this->uid;
//            $map3['status']=1;
//            $mArr=model('merchant')->where($map3)->column('id');
//            if($mArr){
//                $map['a.mer_id']=['in',$mArr];
//            }else{
//                $map['a.mer_id']=0;
//            }
//        }

        $orderDy='a.id desc';
        if(!empty($orderb)){
            if($orderb==1){
                $orderDy='balance asc';
            }elseif($orderb==2){
                $orderDy='balance desc';
            }elseif($orderb==3){
                $orderDy='price asc';
            }elseif($orderb==4){
                $orderDy='price desc';
            }
        }

        if($status==1){
            $map['a.status']=1;
            $map['b.status']=1;
            $map['a.start_time']=['<=',$times];
            $map['a.end_time']=['>=',$times];
            $map['b.balance']=['>=',100];

            $weekObj=new \DateTime($times);
            $nowWeek= $weekObj->format('w');

            $mapb='find_in_set("'.$nowWeek.'",week_day) or week_day= ""';

            $infos = model('push')->alias('a')
                ->join('merchant b','b.id=a.mer_id')
                ->field('count(a.id) num,a.city,sum(a.up_limit) up_limit,sum(balance) balance,avg(price) price')
                ->where($map)
                ->where($mapa)
                ->where($mapb)
                ->order($orderDy)->group('a.city')->paginate(70);
        }elseif($status==2){
            $infos = model('push')->alias('a')
                ->join('merchant b','b.id=a.mer_id')
                ->field('count(a.id) num,a.city,sum(a.up_limit) up_limit,sum(balance) balance,avg(price) price')
                ->where($map)
                ->where($mapa)
                ->where("a.status=2 or b.status=2 or a.start_time >='".date('Y-m-d H:i:s')."' or a.end_time <='".date('Y-m-d H:i:s')."'")
                ->order($orderDy)->group('a.city')->paginate(70);
        }else{
            $infos = model('push')->alias('a')
                ->join('merchant b','b.id=a.mer_id')
                ->field('count(a.id) num,a.city,sum(a.up_limit) up_limit,sum(balance) balance,avg(price) price')
                ->where($map)
                ->where($mapa)
                ->order($orderDy)->group('a.city')->paginate(70);
        }



        foreach ($infos as $k=>$v){
//            $pro = Db::name('product')->field('name')->where(['id'=>$v['pro_id']])->find();
//            $infos[$k]['pro_name'] = $pro['name'] ?? '';
//            $mer = Db::name('merchant')->field('mer_name')->where(['id'=>$v['mer_id']])->find();
//            $infos[$k]['mer_name'] = $mer['mer_name'] ?? '';
            $infos[$k]['num']=$v['num'];
            $infos[$k]['y_push']=0;
            $infos[$k]['dai_push']=$v['up_limit'];
            $infos[$k]['err_push']=0;
            $infos[$k]['stock_push']=0;
            $infos[$k]['price']=round($v['price']);


            $infos[$k]['y_push']=model('clue')->alias('a')
                ->join('account b','b.adv_id=a.adv_id')
                ->where('a.city',$v['city'])->where($map2)->where('a.status',1)->whereTime('a.create_time','d')->count();
            $infos[$k]['all_push']=model('clue')->where('city',$v['city'])->where($map5)->where('status',1)->whereTime('create_time','d')->count();
            $infos[$k]['err_push']=model('clue')->where('city',$v['city'])->where($map1)->where('status',0)->whereTime('create_time','d')->count();
            $infos[$k]['stock_push']=model('clue')->where('city',$v['city'])->where($map1)->where('status',0)->count();
            $infos[$k]['dai_push']=$v['up_limit']-$infos[$k]['all_push'];

            $start3=strtotime(date('Y-m-d',strtotime('-3 day'))) ;
            $start7=strtotime(date('Y-m-d',strtotime('-7 day'))) ;
            $end3=strtotime(date('Y-m-d'))-1 ;

            $chengbenTime=date('Y-m-d',strtotime('-30 day'));
            $end4=date('Y-m-d');

            $infos[$k]['push3']=round(model('clue')->where('city',$v['city'])->where($map1)->whereTime('create_time', 'between', [$start3, $end3])->count()/3,1);
            $infos[$k]['push7']=round(model('clue')->where('city',$v['city'])->where($map1)->whereTime('create_time', 'between', [$start7, $end3])->count()/7,1);
            $chengBen=model('clue_cost_log')->alias('a')
                ->join('account b','b.id=a.account_id')
                ->field('sum(a.money) money,sum(a.transform_val) transform_val')->where('a.city',$v['city'])->where($map4)->whereTime('a.create_time', 'between', [$chengbenTime, $end4])->find();
            if(empty($chengBen['money'])){
                $chengBen['money']=0;
            }
            if(empty($chengBen['transform_val'])){
                $chengBen['transform_val']=0;
            }
            if($chengBen['transform_val']>0){
                $infos[$k]['chengben']=round(bcdiv($chengBen['money'],$chengBen['transform_val'],2));
            }else{
                $infos[$k]['chengben']=0;
            }
            if($v['price']>0){
                $infos[$k]['yugunum']=bcdiv($v['balance'],$v['price']);
            }else{
                $infos[$k]['yugunum']=0;
            }
            if(in_array($this->group_id,[4,5,6])){
                if ($v['balance']>=5000){
                    $balance='****';
                }else{
                    $balance=round($v['balance']);
                }
                $infos[$k]['balance']=$balance;
            }else{
                $infos[$k]['balance']=round($v['balance']);
            }

            //符合规则的商家
            $merchant=model('push')->alias('a')->where($map3)->where($mapa)->where(['city'=>$v['city'],'status'=>1])->select();
            //复购商家
            $infos[$k]['re_num']=0;
            //查询商家充值
            foreach ($merchant as $vv){
                $logList=model('charge')->where('mer_id',$vv['mer_id'])->where('fz_money','>=',500)->limit(2)->select();
                if(count($logList)==2){
                    $infos[$k]['re_num']+=1;
                }
            }

            $infos[$k]['re_num_rate']=bcdiv($infos[$k]['re_num'],$infos[$k]['num'],4)*100;

            $ids = explode('-',$v['city']);
            $cityNum=count($ids);
            if($cityNum==1){
                $infos[$k]['city'] = $this->getCityName($ids[0]);
                $infos[$k]['city_remark']=Db::name('city')->where('id',$ids[0])->value('remark');
            }elseif ($cityNum==2){
                $prov = $this->getCityName($ids[0]);
                $city = $this->getCityName($ids[1]);
                if($prov == $city){
                    $infos[$k]['city'] = $prov;
                }else{
                    $infos[$k]['city'] = $prov.'-'.$city;

                }
                $infos[$k]['city_remark']=Db::name('city')->where('id',$ids[1])->value('remark');
            }

            $infos[$k]['time']=date('Y-m-d');
        }

        $provinces = Db::name('city')->where(['pid'=>1])->select();
        $products = model('Product')->getListByMap();
//        $merchants = model('Merchant')->getListByMap([],'','',false);
        $channels = $this->getChannelArray();

        if(is_array($channel_id)){
            $channel_id=implode(',',$channel_id);
        }else{
            $channel_id=0;
        }
        if(is_array($account_id)){
            $account_id=implode(',',$account_id);
        }else{
            $account_id=0;
        }

        $account=model('Account')->getListByMap([],'id,acc_name,channel_id');

        $accountTree=[];
        foreach ($channels as $k=>$v){
            $temp['id']=$k;
            $temp['name']=$v;
            $temp['sub']=[];
            foreach ($account as $key=>$val){
                if($val['channel_id']==$k){
                    $temp['sub'][]=['id'=>$val['id'],'name'=>$val['acc_name']];
                }
            }
            $accountTree[]=$temp;
        }


        return $this->fetch('',[
            'infos' => $infos,
//            'pro_name' => $pro_name,
            'province' => $provinces,
            'sprovince' => $province,
            'orderb' => $orderb,
            'status' => $status,
            'channel_id' => $channel_id,
            'pro_id' => $pro_id,
            'products' => $products,
            'channels' => $channels,
            'group_id' => $this->group_id,
            'account' => $account,
            'type' => $type,
            'account_id' => $account_id,
            'accountTree' => $accountTree,
            'times' => $times,
        ]);
    }

    //线索需求导出
    public function clueDemandExport(){

        $province = input('province','');
        $orderb = input('orderb','');
        $status = input('status/d',1);
        $channel_id = input('channel_id/a',0);
        $account_id = input('account_id/a',0);
        $pro_id = input('pro_id/d',0);
        $type = input('type',2);
        $times = input('times',date('Y-m-d'));

        $map = [];

        $map1=[];
        $map2=[];
        $map3=[];
        $map4=[];
        $mapa=[];
        $map5=[];
        if(!empty($province)){
            $map['a.city']=['like',$province.'-'.'%'];
        }

        if($type==1){
            if(!empty($channel_id)){
                $channel_id=explode(',',$channel_id);
                if(count($channel_id)==1&&$channel_id[0]==0){

                }else{
//                $map['a.channel_id']=['in',$channel_id];
//                $mapa='find_in_set(channel_id, "'.implode(',', $channel_id).'")';

                    $channelStr=[];
                    foreach ($channel_id as $v){
                        $channelStr[]='find_in_set("'.$v.'",channel_id)';
                    }
                    $mapa=implode(' or ',$channelStr);

                    $map1['type']=['in',$channel_id];
                    $map2['channel_id']=['in',$channel_id];
//                $map3['channel_id']=['in',$channel_id];
                    $map4['channel_id']=['in',$channel_id];
                }
            }
        }elseif($type==2){
            if(!empty($account_id)){
                $account_id=explode(',',$channel_id);
                if(count($account_id)==1&&$account_id[0]==0){

                }else{
//                $map['a.channel_id']=['in',$channel_id];
//                $mapa='find_in_set(channel_id, "'.implode(',', $channel_id).'")';

                    $channelStr=[];
                    foreach ($account_id as $v){
                        $channelStr[]='find_in_set("'.$v.'",account_id)';
                    }
                    $mapa=implode(' or ',$channelStr);

                    $map1['account_id']=['in',$account_id];
                    $map2['account_id']=['in',$account_id];
//                $map3['channel_id']=['in',$channel_id];
                    $map4['account_id']=['in',$account_id];
                }
            }
        }

        if(!empty($pro_id)){
            $map['a.pro_id']=$pro_id;
            $map1['pro_id']=$pro_id;
            $map2['pro_id']=$pro_id;
            $map3['pro_id']=$pro_id;
            $map4['pro_id']=$pro_id;
            $map5['pro_id']=$pro_id;
        }

//        if(in_array($this->group_id,[4,5])){
//            $map3['bind_aid|weihu_aid']=$this->uid;
//            $map3['status']=1;
//            $mArr=model('merchant')->where($map3)->column('id');
//            if($mArr){
//                $map['a.mer_id']=['in',$mArr];
//            }else{
//                $map['a.mer_id']=0;
//            }
//        }

        $orderDy='a.id desc';
        if(!empty($orderb)){
            if($orderb==1){
                $orderDy='balance asc';
            }elseif($orderb==2){
                $orderDy='balance desc';
            }elseif($orderb==3){
                $orderDy='price asc';
            }elseif($orderb==4){
                $orderDy='price desc';
            }
        }


        if($status==1){
            $map['a.status']=1;
            $map['b.status']=1;
            $map['a.start_time']=['<=',$times];
            $map['a.end_time']=['>=',$times];
            $map['b.balance']=['>=',100];

            $infos = model('push')->alias('a')
                ->join('merchant b','b.id=a.mer_id')
                ->field('count(a.id) num,a.city,sum(a.up_limit) up_limit,sum(balance) balance,avg(price) price')
                ->where($map)
                ->where($mapa)
                ->order($orderDy)->group('a.city')->select();
        }elseif($status==2){
            $infos = model('push')->alias('a')
                ->join('merchant b','b.id=a.mer_id')
                ->field('count(a.id) num,a.city,sum(a.up_limit) up_limit,sum(balance) balance,avg(price) price')
                ->where($map)
                ->where($mapa)
                ->where("a.status=2 or b.status=2 or start_time >='".date('Y-m-d H:i:s')."' or end_time <='".date('Y-m-d H:i:s')."'")
                ->order($orderDy)->group('a.city')->select();
        }else{
            $infos = model('push')->alias('a')
                ->join('merchant b','b.id=a.mer_id')
                ->field('count(a.id) num,a.city,sum(a.up_limit) up_limit,sum(balance) balance,avg(price) price')
                ->where($map)
                ->where($mapa)
                ->order($orderDy)->group('a.city')->select();
        }

        if(empty($infos)){
            echo '没有数据导出';
        }

        foreach ($infos as $k=>$v){
//            $pro = Db::name('product')->field('name')->where(['id'=>$v['pro_id']])->find();
//            $infos[$k]['pro_name'] = $pro['name'] ?? '';
//            $mer = Db::name('merchant')->field('mer_name')->where(['id'=>$v['mer_id']])->find();
//            $infos[$k]['mer_name'] = $mer['mer_name'] ?? '';
            $infos[$k]['num']=$v['num'];
            $infos[$k]['y_push']=0;
            $infos[$k]['dai_push']=$v['up_limit'];
            $infos[$k]['err_push']=0;
            $infos[$k]['stock_push']=0;
            $infos[$k]['price']=round($v['price']);


            $infos[$k]['y_push']=model('clue')->alias('a')
                ->join('account b','b.adv_id=a.adv_id')
                ->where('a.city',$v['city'])->where($map2)->where('a.status',1)->whereTime('a.create_time','d')->count();
            $infos[$k]['all_push']=model('clue')->where('city',$v['city'])->where($map5)->where('status',1)->whereTime('create_time','d')->count();
            $infos[$k]['err_push']=model('clue')->where('city',$v['city'])->where($map1)->where('status',0)->whereTime('create_time','d')->count();
            $infos[$k]['stock_push']=model('clue')->where('city',$v['city'])->where($map1)->where('status',0)->count();
            $infos[$k]['dai_push']=$v['up_limit']-$infos[$k]['all_push'];

            $start3=strtotime(date('Y-m-d',strtotime('-3 day'))) ;
            $start7=strtotime(date('Y-m-d',strtotime('-7 day'))) ;
            $end3=strtotime(date('Y-m-d'))-1 ;

            $chengbenTime=date('Y-m-d',strtotime('-30 day'));
            $end4=date('Y-m-d');

            $infos[$k]['push3']=round(model('clue')->where('city',$v['city'])->where($map1)->whereTime('create_time', 'between', [$start3, $end3])->count()/3,1);
            $infos[$k]['push7']=round(model('clue')->where('city',$v['city'])->where($map1)->whereTime('create_time', 'between', [$start7, $end3])->count()/7,1);
            $chengBen=model('clue_cost_log')->alias('a')
                ->join('account b','b.id=a.account_id')
                ->field('sum(a.money) money,sum(a.transform_val) transform_val')->where('a.city',$v['city'])->where($map4)->whereTime('a.create_time', 'between', [$chengbenTime, $end4])->find();
            if(empty($chengBen['money'])){
                $chengBen['money']=0;
            }
            if(empty($chengBen['transform_val'])){
                $chengBen['transform_val']=0;
            }
            if($chengBen['transform_val']>0){
                $infos[$k]['chengben']=round(bcdiv($chengBen['money'],$chengBen['transform_val'],2));
            }else{
                $infos[$k]['chengben']=0;
            }
            if($v['price']>0){
                $infos[$k]['yugunum']=bcdiv($v['balance'],$v['price']);
            }else{
                $infos[$k]['yugunum']=0;
            }
            if(in_array($this->group_id,[4,5,6])){
                if ($v['balance']>=5000){
                    $balance='****';
                }else{
                    $balance=round($v['balance']);
                }
                $infos[$k]['balance']=$balance;
            }else{
                $infos[$k]['balance']=round($v['balance']);
            }

            //符合规则的商家
            $merchant=model('push')->alias('a')->where($map3)->where($mapa)->where(['city'=>$v['city'],'status'=>1])->select();
            //复购商家
            $infos[$k]['re_num']=0;
            //查询商家充值
            foreach ($merchant as $vv){
                $logList=model('charge')->where('mer_id',$vv['mer_id'])->where('fz_money','>=',500)->limit(2)->select();
                if(count($logList)==2){
                    $infos[$k]['re_num']+=1;
                }
            }

            $infos[$k]['re_num_rate']=bcdiv($infos[$k]['re_num'],$infos[$k]['num'],4)*100;

            $ids = explode('-',$v['city']);
            $cityNum=count($ids);
            if($cityNum==1){
                $infos[$k]['city'] = $this->getCityName($ids[0]);
                $infos[$k]['city_remark']=Db::name('city')->where('id',$ids[0])->value('remark');
            }elseif ($cityNum==2){
                $prov = $this->getCityName($ids[0]);
                $city = $this->getCityName($ids[1]);
                if($prov == $city){
                    $infos[$k]['city'] = $prov;
                }else{
                    $infos[$k]['city'] = $prov.'-'.$city;

                }
                $infos[$k]['city_remark']=Db::name('city')->where('id',$ids[1])->value('remark');
            }

            $infos[$k]['time']=date('Y-m-d');
        }


        $newExcel = new Spreadsheet();
//获取当前操作sheet的对象
        $objSheet = $newExcel->getActiveSheet();
        $date = date('Ymd',time());
        $name = '订单信息表';
        $objSheet->setTitle($name);//设置当前sheet的标题
//设置表头

        if(in_array($this->group_id,[4,5])){
            $objSheet->setCellValue('A1', '城市')
                ->setCellValue('B1', '规则数量')
                ->setCellValue('C1', '账户币余额')
                ->setCellValue('D1', '时间');

            $objSheet->getColumnDimension('A')->setWidth(20);
            $objSheet->getColumnDimension('B')->setWidth(10);
            $objSheet->getColumnDimension('C')->setWidth(20);
            $objSheet->getColumnDimension('D')->setWidth(20);

            $info = $infos;
            $dataCount = count($info);
            $k = 1;
            if($dataCount == 0){
                exit;
            }else {
                for ($i = 0; $i < $dataCount; $i++) {
                    $k = $k + 1;
                    $objSheet->setCellValue('A' . $k, $info[$i]['city'])
                        ->setCellValue('B' . $k, $info[$i]['num'])
                        ->setCellValue('C' . $k, $info[$i]['balance'])
                        ->setCellValue('D' . $k, $info[$i]['time']);
                }
            }
        }else{
            $objSheet->setCellValue('A1', '城市')
                ->setCellValue('B1', '规则数量')
                ->setCellValue('C1', '平均单价')
                ->setCellValue('D1', '账户币余额')
                ->setCellValue('E1', '今日接收上限')
                ->setCellValue('F1', '今日剩余推送')
                ->setCellValue('G1', '今日已推送')
                ->setCellValue('H1', '前3日进线量')
                ->setCellValue('I1', '前7日进线量')
                ->setCellValue('J1', '今日推送失败')
                ->setCellValue('K1', '库存线索')
                ->setCellValue('L1', '时间');

            $objSheet->getColumnDimension('A')->setWidth(20);
            $objSheet->getColumnDimension('B')->setWidth(10);
            $objSheet->getColumnDimension('C')->setWidth(20);
            $objSheet->getColumnDimension('D')->setWidth(15);
            $objSheet->getColumnDimension('E')->setWidth(15);
            $objSheet->getColumnDimension('F')->setWidth(15);
            $objSheet->getColumnDimension('G')->setWidth(15);
            $objSheet->getColumnDimension('H')->setWidth(15);
            $objSheet->getColumnDimension('I')->setWidth(15);
            $objSheet->getColumnDimension('J')->setWidth(15);
            $objSheet->getColumnDimension('K')->setWidth(15);
            $objSheet->getColumnDimension('L')->setWidth(20);

            $info = $infos;
            $dataCount = count($info);
            $k = 1;
            if($dataCount == 0){
                exit;
            }else {
                for ($i = 0; $i < $dataCount; $i++) {
                    $k = $k + 1;
                    $objSheet->setCellValue('A' . $k, $info[$i]['city'])
                        ->setCellValue('B' . $k, $info[$i]['num'])
                        ->setCellValue('C' . $k, $info[$i]['price'])
                        ->setCellValue('D' . $k, $info[$i]['balance'])
                        ->setCellValue('E' . $k, $info[$i]['up_limit'])
                        ->setCellValue('F' . $k, $info[$i]['dai_push'])
                        ->setCellValue('G' . $k, $info[$i]['y_push'])
                        ->setCellValue('H' . $k, $info[$i]['push3'])
                        ->setCellValue('I' . $k, $info[$i]['push7'])
                        ->setCellValue('J' . $k, $info[$i]['err_push'])
                        ->setCellValue('K' . $k, $info[$i]['stock_push'])
                        ->setCellValue('L' . $k, $info[$i]['time']);
                }
            }
        }

        $filename = date('Y-m-d').'线索需求导出';
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename='.$filename.'.xlsx');
        header('Cache-Control: max-age=0');
//
        $write = IOFactory::createWriter($newExcel, 'Xlsx');
        $write->save('php://output');

    }

    //没有需求的线索
    public function undefinedDemand(){
//        $pro_name = input('pro_name','');
        $province = input('province','');

        $map = [];
//        if($pro_name != ''){
//            $products = Db::name('product')->field('id')->where(['name'=>['like','%'.$pro_name.'%']])->select();
//            $pro_id_list = array_column($products, 'id');
//            $map['pro_id'] = ['in',$pro_id_list];
//        }

        if(!empty($province)){
            $map['city']=['like',$province.'-'.'%'];
        }

        $map['status'] = 0;

        $quyu=model('push')->where('status',1)->group('city')->column('city');
        $infos=model('clue')
            ->field('city,count(id) num')
            ->whereNotIn('city',$quyu)->where($map)->order('id desc')->group('city')->paginate();
//
//        $infos = model('push')
//            ->field('count(id) num,city,sum(up_limit) up_limit')
//            ->where($map)->order('id desc')->group('city')->paginate();
//        dump($infos);die;

//        dump($map);die;

        foreach ($infos as $k=>$v){
//
            $infos[$k]['err_push']=model('clue')->where('city',$v['city'])->where('status',0)->whereTime('create_time','d')->count();
            $ids = explode('-',$v['city']);
            $cityNum=count($ids);
            if($cityNum==1){
                $infos[$k]['city'] = $this->getCityName($ids[0]);
            }elseif ($cityNum==2){
                $prov = $this->getCityName($ids[0]);
                $city = $this->getCityName($ids[1]);
                if($prov == $city){
                    $infos[$k]['city'] = $prov;
                }else{
                    $infos[$k]['city'] = $prov.'-'.$city;
                }
            }

            $infos[$k]['time']=date('Y-m-d');
        }

        $province = Db::name('city')->where(['pid'=>1])->select();
//        $products = model('Product')->getListByMap();
//        $merchants = model('Merchant')->getListByMap([],'','',false);

        return $this->fetch('',[
            'infos' => $infos,
//            'pro_name' => $pro_name,
            'province' => $province,
        ]);
    }


    //黑名单
    public function backStatus()
    {
//        $bool=$this->tokenBucket($this->uid,'adminDel',5,1);
//        if(!$bool){
//            return $this->showReturnCode(1009,'请勿频繁操作');
//        }
        if($this->request->isAjax()){
            $id = input('post.id');
            $status = input('status');
            $model = $this->request->controller();

            $res = model($model)->where('id',$id)->update(['is_black'=>$status]);
            if($res){
                $this->RecordSystemLog($this->uid,$this->behavior,'黑名单'.$status.'成功,操作ID: '.$id);
                if($status==1){
                    return $this->showReturnCode(1001,'加入成功');

                }else{
                    return $this->showReturnCode(1001,'取消成功');

                }
            }else{
                return $this->showReturnCode(1009,'删除失败');
            }
        }else{
            return $this->showReturnCode(1002);
        }
    }


    /**
     * 软删除
     */
    public function delete()
    {
//        $bool=$this->tokenBucket($this->uid,'adminDel',5,1);
//        if(!$bool){
//            return $this->showReturnCode(1009,'请勿频繁操作');
//        }
        if($this->request->isAjax()){
            $id = input('post.id');
            $model = $this->request->controller();

            $res = model($model)->where('id',$id)->delete();
            if($res){
                Db::name('clue_log')->where('clue_id',$id)->delete();
                $this->RecordSystemLog($this->uid,$this->behavior,'删除成功,操作ID: '.$id);
                return $this->showReturnCode(1001);
            }else{
                return $this->showReturnCode(1009,'删除失败');
            }
        }else{
            return $this->showReturnCode(1002);
        }
    }
    /**
     * 软删除
     */
    public function delete2()
    {
        $bool=$this->tokenBucket($this->uid,'adminDel',5,1);
        if(!$bool){
            return $this->showReturnCode(1009,'请勿频繁操作');
        }
        if($this->request->isAjax()){
            $id = input('post.id');
            $model = $this->request->controller();

            $res = model($model)->where('id',$id)->delete();
            if($res){
                $info=Db::name('clue_log')->where('clue_id',$id)->select();
                foreach ($info as $v){
                    Db::name('clue_log')->where('id',$v['id'])->delete();
                    if($v['price']>0){
                        Db::name('merchant')->where('id',$v['mer_id'])->inc('balance',$v['price'])->inc('balance2',$v['price'])->update();
                        $merInfo=Db::name('merchant')->where('id',$v['mer_id'])->find();
                        $balanceLog[]=['mer_id'=>$merInfo['id'],'change_type'=>1,'type'=>1,'money'=>$v['price'],'balance'=>$merInfo['balance'],'create_time'=>time(),'remark'=>'撤回线索'];
                        $balanceLog[]=['mer_id'=>$merInfo['id'],'change_type'=>1,'type'=>2,'money'=>$v['price'],'balance'=>$merInfo['balance2'],'create_time'=>time(),'remark'=>'撤回线索'];
                        Db::name('merchant_balance_log')->insertAll($balanceLog);
                    }
                }
                $this->RecordSystemLog($this->uid,$this->behavior,'删除成功,操作ID: '.$id);
                return $this->showReturnCode(1001);
            }else{
                return $this->showReturnCode(1009,'删除失败');
            }
        }else{
            return $this->showReturnCode(1002);
        }
    }

    //测回线索
    public function backPushClue(){
        $bool=$this->tokenBucket($this->uid,'backPushClue',5,1);
        if(!$bool){
            return $this->showReturnCode(1009,'请勿频繁操作');
        }
        if($this->request->isAjax()){
            $id = input('post.id');
            $model = $this->request->controller();

            $res = model($model)->where('id',$id)->update(['status'=>0,'err_msg'=>'推送撤回']);
            if($res){
                $info=Db::name('clue_log')->where('clue_id',$id)->select();
                foreach ($info as $v){
                    Db::name('clue_log')->where('id',$v['id'])->delete();
                    if($v['price']>0){
                        Db::name('merchant')->where('id',$v['mer_id'])->inc('balance',$v['price'])->inc('balance2',$v['price'])->update();
                        $merInfo=Db::name('merchant')->where('id',$v['mer_id'])->find();
                        $balanceLog[]=['mer_id'=>$merInfo['id'],'change_type'=>1,'type'=>1,'money'=>$v['price'],'balance'=>$merInfo['balance'],'create_time'=>time(),'remark'=>'撤回线索'];
                        $balanceLog[]=['mer_id'=>$merInfo['id'],'change_type'=>1,'type'=>2,'money'=>$v['price'],'balance'=>$merInfo['balance2'],'create_time'=>time(),'remark'=>'撤回线索'];
                        Db::name('merchant_balance_log')->insertAll($balanceLog);
                        (new \app\common\model\Merchant())->changeBalance($v['mer_id'], $v['price']); //账户余额币 变化 业务逻辑
                    }
                }
                $this->RecordSystemLog($this->uid,$this->behavior,'撤回成功,操作ID: '.$id);
                return $this->showReturnCode(1001);
            }else{
                return $this->showReturnCode(1009,'撤回失败');
            }
        }else{
            return $this->showReturnCode(1002);
        }
    }

    //线索导入
    public function importClue(){
        $fileInfo = request()->file('file');

        if($fileInfo){
            $info = $fileInfo->move(ROOT_PATH . 'public' . DS . 'uploads');
            if($info){
                $file=ROOT_PATH . 'public' . DS . 'uploads/'.$info->getSaveName();

                // 自动获取文件类型
                $file_type = \PhpOffice\PhpSpreadsheet\IOFactory::identify($file);
                // 创建读操作
                if ($file_type == 'Xlsx') {
                    $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx');
                } else {
                    $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xls');
                }

                // 打开文件、载入excel表格
                $spreadsheet = $reader->load($file);

                // 获取活动工作薄
                $sheet = $spreadsheet->getActiveSheet();


                //获取所有内容并转化为数组
                $data = $sheet->toArray();

                //验证数据
                $title=$data[0];
                $errMsg='表格格式头错误格式应为【账户ID,产品,线索名称,电话,城市,申请额度,备注】';
                if(count($title)<7){
                    return $this->showReturnCode(1011,$errMsg);
                }
                foreach ($title as $k=>$v){
                    $lie=$k+1;
                    if($k==0){
                        if($v!='账户ID'){
                            return $this->showReturnCode(1011,'第'.$lie.'列：'.$errMsg);
                        }
                    }
                    if($k==1){
                        if($v!='产品'){
                            return $this->showReturnCode(1011,'第'.$lie.'列：'.$errMsg);
                        }
                    }
                    if($k==2){
                        if($v!='线索名称'){
                            return $this->showReturnCode(1011,'第'.$lie.'列：'.$errMsg);
                        }
                    }
                    if($k==3){
                        if($v!='电话'){
                            return $this->showReturnCode(1011,'第'.$lie.'列：'.$errMsg);
                        }
                    }
                    if($k==4){
                        if($v!='城市'){
                            return $this->showReturnCode(1011,'第'.$lie.'列：'.$errMsg);
                        }
                    }
                    if($k==5){
                        if($v!='申请额度'){
                            return $this->showReturnCode(1011,'第'.$lie.'列：'.$errMsg);
                        }
                    }
                    if($k==6){
                        if($v!='备注'){
                            return $this->showReturnCode(1011,'第'.$lie.'列：'.$errMsg);
                        }
                    }
                }

                $productArr=model('Product')->column('id','name');

                $product=array_keys($productArr);

                unset($data[0]);
                $num=count($data);

                $insertData=[];
                Db::startTrans();
                foreach ($data as $kk=>$vv){
                    $nowNum=$kk+1;

                    if(empty($vv[0])&&empty($vv[1])&&empty($vv[2])&&empty($vv[3])&&empty($vv[4])&&empty($vv[5])&&empty($vv[6])){
                        continue;
                    }

//                    if(!is_numeric($vv[3])){
//                        return $this->showReturnCode(1011,'展示量应为数字【'.$vv[3].'】错误:第'.$nowNum.'行');
//                    }
//                    if(!is_numeric($vv[4])){
//                        return $this->showReturnCode(1011,'点击应为数字【'.$vv[4].'】错误:第'.$nowNum.'行');
//                    }
//                    if(!is_numeric($vv[6])){
//                        return $this->showReturnCode(1011,'转化量应为数字【'.$vv[3].'】错误:第'.$nowNum.'行');
//                    }

                    $account=Db::name('account')->where('adv_id',$vv[0])->find();
                    if(empty($account)){
                        return $this->showReturnCode(1011,'账户ID【'.$vv[0].'】错误:第'.$nowNum.'行');
                    }

                    if (strpos($vv[4], '|') !== false) {
                        $city_t = explode('|',$vv[4]);
                    } else if(strpos($vv[4], '-') !== false) {
                        $city_t = explode('-',$vv[4]);
                    } else if(strpos($vv[4], ' ') !== false) {
                        $city_t = explode(' ',$vv[4]);
                    }else{
                        $city_t = [$vv[4]];
                    }

//                    if(count($city_t) == 3){
//                        $vv[4] = $city_t[1];
//                    }elseif(count($city_t) == 2){
//                        $vv[4] = $city_t[1];
//                    }elseif(count($city_t) == 1){
//                        $vv[4] = $city_t[0];
//                    }

//                    if(strpos($vv[4], '文山') !== false){
//                        $city='文山';
//                    }elseif (strpos($vv[4], '凉山') !== false){
//                        $city='凉山';
//                    }elseif (strpos($vv[4], '巴彦淖尔') !== false){
//                        $city='巴彦淖尔盟';
//                    }elseif (strpos($vv[4], '锡林郭勒') !== false){
//                        $city='锡林郭勒盟';
//                    }else{
                        $city = str_replace('市','',$vv[4] ?? '');
//                    }
//
////                    $city = str_replace('市','',$vv[2] ?? '');
//
//                    $city_info = Db::name('city')->where(['type'=>2,'name'=>$city])->find();
                    $city_info = clue_city_transform($city_t);
                    if(!$city_info){
                        return $this->showReturnCode(1011,'城市['.$city.']错误:第'.$nowNum.'行');
                    }
                    if(!in_array($vv[1],$product)){
                        return $this->showReturnCode(1011,'产品['.$vv[1].']错误:产品应为('.implode(',',$product).')第'.$nowNum.'行');
                    }
                    $province = Db::name('city')->where(['id'=>$city_info['pid']])->find();
                    $city = $province['id'].'-'.$city_info['id'];

                    $isData=Db::name('Clue')->where(['adv_id'=>$vv[0],'pro_id'=>$productArr[$vv[1]],'clue_name'=>$vv[2],'phone'=>$vv[3],'city'=>$city])->whereTime('create_time', 'today')->find();
                    if($isData){
                        Db::rollback();
                        return $this->showReturnCode(1011,'导入失败，线索：['.$vv[1].']['.$vv[2].']['.$vv[3].']['.$vv[4].']已存在！第'.$nowNum.'行');

                    }else{

                        $insertData[]=[
                            'clue_id'=>time().mt_rand(1,999999).$k,
                            'clue_name'=>$vv[2],
                            'adv_id'=>$account['adv_id'],
                            'type'=>$account['channel_id'],
                            'pro_id'=>$productArr[$vv[1]],
                            'city'=>$city,
                            'phone'=>$vv[3],
                            'apply_limit'=>$vv[5],
                            'remark'=>$vv[6],
                            'create_time'=>time(),
                        ];
                    }
                }

//                die;
                if($insertData){
                    $bool=$this->tokenBucket($this->uid,'ClueImport',60,1);
                    if(!$bool){
                        Db::rollback();
                        return $this->showReturnCode(1009,'请勿频繁操作，每分钟最多导入1次');
                    }
                    $clueArr=model('Clue')->saveAll($insertData);
                    Db::commit();

                    // 1.当前任务将由哪个类来负责处理。
                    // 当轮到该任务时，系统将生成一个该类的实例，并调用其 fire 方法
                    $jobHandlerClassName  = 'app\job\ExprotClue@fire';
                    // 2.当前任务归属的队列名称，如果为新队列，会自动创建
                    $jobQueueName     = "ExprotClue";
                    $time2wait=mt_rand(30,60);
                    foreach ($clueArr as $v) {
                        $jobData = ['id'=>$v['id']];
                        $isPushed = Queue::later($time2wait, $jobHandlerClassName, $jobData, $jobQueueName);
                        $time2wait += mt_rand(300,600);
                    }
                    return $this->showReturnCode(1001,'导入成功');
                }else{
                    Db::rollback();
                    return $this->showReturnCode(1011,'导入数据不能为空');
                }

            }else{
                return $this->showReturnCode(1009,'上传失败');
            }
        }else{
            return $this->showReturnCode(1009,'上传失败');
        }
    }

    public function dayTime()
    {
        // 查询条件start

        $start_time = input('start_time');
        $end_time = input('end_time');
        $channel_id = input('channel_id',0);
        $account_id = input('account_id',0);


        $map = [];

        if($start_time != null && $end_time != null){
            $start = strtotime($start_time);
            $end = strtotime($end_time);
            if($end > $start) $map['a.create_time'] = ['between',[$start,$end]];
        }elseif ($start_time != null && empty($end_time) ){
            $start = strtotime($start_time);
            $map['a.create_time'] = ['>=',$start];
        }elseif ( empty($start_time) && $end_time != null ){
            $end = strtotime($end_time);
            $map['a.create_time'] = ['<=',$end];
        }else{
            $start_time=date('Y-m-d'). ' 00:00:00';
            $end_time=date('Y-m-d').' 23:59:59';
            $start=strtotime($start_time);
            $end=strtotime($end_time);
            $map['a.create_time']= ['between',[$start,$end]];
        }

        if(!empty($channel_id)){
            $channel_arr=explode(',',$channel_id);
            $map['type']=['in',$channel_arr];
        }

        if(!empty($account_id)){
            $account_arr=explode(',',$account_id);
            $map['account_id']=['in',$account_arr];
        }


        // 查询条件end

//        $systemLogs = model('ClueErrorLog')->getInfosByMap($map, '', false);

        $systemLogs = model('Clue')->alias('a')->field('count(a.id) num,FROM_UNIXTIME(create_time,"%H") as time')
            ->group('time')
            ->where($map)
            ->order('time asc')->select();


        $ChannelArr = model('Channel')->column('name','id');
        $channel=[];
        foreach ($ChannelArr as $k=>$v){
            $channel[]=['name'=>$v,'value'=>$k];
        }

        $account=model('Account')->getListByMap([],'id value,acc_name name');

        $channelStr=json_encode($channel,JSON_UNESCAPED_UNICODE);
        $accountStr=json_encode($account,JSON_UNESCAPED_UNICODE);

//        dump($systemLogs);die;

        $allNum=0;
        if($systemLogs){
            $allNum=array_sum(array_column($systemLogs,'num'));
            foreach ($systemLogs as &$v){
                $time=intval($v['time']);
                $v['time']=sprintf("%02d", $time).':00 - '.sprintf("%02d", $time+1).': 00';
                $v['rate']=bcdiv($v['num'],$allNum,4)*100;
            }
        }



        if(empty($channel_id)){
            $channel_id=0;
        }else{
//            $channel_id=$channel_arr;
        }

        if(empty($account_id)){
            $account_id=0;
        }else{
//            $account_id=$account_arr;
        }


        return $this->fetch('', [
            'systemLogs' => $systemLogs,
            'start_time' => $start_time,
            'end_time' => $end_time,
            'allNum' => $allNum,
            'channel' => $channelStr,
            'account' => $accountStr,
            'channel_id' => $channel_id,
            'account_id' => $account_id,
        ]);
    }

    public function addClue()
    {
        if(request()->isAjax()){
            try{
                $save_data = input('post.');

                if (empty($save_data['clue_name'])) {
                    return self::showReturnCode(1011, '姓名必填');
                }
                if (empty($save_data['phone'])) {
                    return self::showReturnCode(1011, '手机必填');
                }
                if (empty($save_data['adv_id'])) {
                    return self::showReturnCode(1011, '请选择投放账户');
                }
                if (empty($save_data['pro_id'])) {
                    return self::showReturnCode(1011, '请选择产品');
                }
                if (empty($save_data['apply_limit'])) {
                    return self::showReturnCode(1011, '申请金额必填');
                }

                $account = \db('account')->where('adv_id', $save_data['adv_id'])->find(); // 投放账号信息
                if (empty($account) || $account['status'] == 2) {
                    return self::showReturnCode(1011, '投放账号不存在或账号已被停用');
                }

                $city = $save_data['province']."-".$save_data['city'];
                //城市是否禁用
                $isCity = model('accountCity')->where(['acc_id' => $account['id'], 'city' => $city, 'status' => 1])->find();
                if (!empty($isCity)) {
                    return self::showReturnCode(1011, '账户城市已禁用');
                }

                // 城市是否准入
                $is_allow = (new \app\common\model\Clue())->allowAccountCity($account['id'], $city);
                if ($is_allow === false) {
                    return self::showReturnCode(1011, '账户城市不准入');
                }

                $isDayPhone = (new \app\common\model\Clue())->isRepeatClue($save_data['phone'], $save_data['adv_id']);
                if ($isDayPhone) {
                    return self::showReturnCode(1011, '当天线索已存在');
                }
                $time = time();
                $save_data['city'] = $city;
                $save_data['source'] = "后台添加";
                $save_data['type'] = $account['channel_id']; // 对应媒体渠道表channel_id
                $save_data['clue_id'] = create_no('AMCJ'); // 自生成线索id
                $save_data['create_time'] = $time;
                $save_data['update_time'] = $time;
                $save_data['account_id'] = $account['id'];

                $remark_arr = [
                    '贷款金额' => $save_data['apply_limit']
                ];
                $detail = ""; // 车房详情字段
                if (!empty($save_data['remark'])) {
                    $remark = explode("\n", $save_data['remark']);
                    $detail = implode("|", $remark);
                    foreach ($remark as $value) {
                        $value_arr = explode(":", $value);
                        $remark_arr[$value_arr[0]] = $value_arr[1];
                    }

                    if (!empty($remark_arr)) {
                        $save_data['remark'] = json_encode($remark_arr, JSON_UNESCAPED_UNICODE);
                    }
                }

                if ($save_data['pro_id'] == 3) {
                    $save_data['house'] = $detail;
                } elseif ($save_data['pro_id'] == 4) {
                    $save_data['car'] = $detail;
                }

                //记录线索成本
                $clueCost = model('ClueAddCost')->where(['account_id' => $account['id'], 'pro_id' => $save_data['pro_id'], 'city' => $city, 'status' => 1])->find();
                if (empty($clueCost)) {
                    // 找不到城市就找默认全国城市
                    $clueCost = model('ClueAddCost')->where(['account_id' => $account['id'], 'pro_id' => $save_data['pro_id'], 'city' => "", 'status' => 1])->find();
                }
                if (!empty($clueCost)) {
                    $price = $clueCost['money'];
                    $true_price = $clueCost['money'];
                    $xz_price = $clueCost['money'];
                    $xz_true_price = $clueCost['money'];
                    $xz_price2 = $clueCost['money'];
                    $xz_true_price2 = $clueCost['money'];
                    $xz_price3 = $clueCost['money'];
                    $xz_true_price3 = $clueCost['money'];
                    $xz_price4 = $clueCost['money'];
                    $xz_true_price4 = $clueCost['money'];
                } else {
                    $price = $account['clue_cost'];
                    $true_price = $account['clue_cost'];
                    $xz_price = $account['clue_cost'];
                    $xz_true_price = $account['clue_cost'];
                    $xz_price2 = $account['clue_cost'];
                    $xz_true_price2 = $account['clue_cost'];
                    $xz_price3 = $account['clue_cost'];
                    $xz_true_price3 = $account['clue_cost'];
                    $xz_price4 = $account['clue_cost'];
                    $xz_true_price4 = $account['clue_cost'];
                }
                // 线索入库
                $price = [
                    'price' => $price,
                    'true_price' => $true_price,
                    'xz_price' => $xz_price,
                    'xz_true_price' => $xz_true_price,
                    'xz_price2' => $xz_price2,
                    'xz_true_price2' => $xz_true_price2,
                    'xz_price3' => $xz_price3,
                    'xz_true_price3' => $xz_true_price3,
                    'xz_price4' => $xz_price4,
                    'xz_true_price4' => $xz_true_price4,
                ];
                $save_data = array_merge($save_data, $price);
                $result = $this->editData(false, '', 'Clue', $save_data);
                if ($result['code'] == 1001) {
                    $result['msg'] = '添加线索成功';
                    $this->RecordSystemLog($this->uid, $this->behavior, '【' . $save_data['phone'] .$save_data['clue_name']  . '】添加线索成功');
                }

                return $result;
            }catch (\Exception $e){
                Log::error($e->getMessage());
                return self::showReturnCode(1011,$e->getMessage());
            }
        }else{
            return self::showReturnCode(1002);
        }
    }
}